I'd like only my base domain www.domain.com to be rewritten to https://www.domain.com By default in my https block I have it reroute to http:// if it's not ~uri = "/" (base domain) or static content.
server {
listen 443;
set $ssltoggle 2;
if ($uri ~ ^/(img|js|css|static)/) {
set $ssltoggle 1;
}
if ($uri = '/') {
set $ssltoggle 1;
}
if ($ssltoggle != 1) {
rewrite ^(.*)$ http://$server_name$1 permanent;
}
}
So in my http block I need to do the rewrite if it has to https:
server {
listen 80;
if ($uri = '/') {
set $ssltoggle 1;
}
if ($ssltoggle = 1) {
rewrite ^(.*)$ https://$server_name$1 permanent;
}
}
If I don't have the $uri = '/' if-statement in the http block, then https works fine if I go directly to it, but I won't get redirected if I go to regular http which is expected. If I do put that in-statement in the http block then everything stops working within minutes. It might work for a few requests, but will always stop within a minute or so. In browsers I just get a blank page for all requests. If I restart nginx it continues to not work until I remove both if-statement blocks in both the https and http blocks and restart nginx. When I look in the error logs I don't see anything logged. When I look in the access log I see this message:
"-" 400 0 "-" "-"
which I assume means a 400 error. I don't understand why this doesn't work for me. My end goal is to have the base domain be https-only while all other pages default to http. How can I achieve this?
I ended up changing the $uri to $request_uri so args can be handled without redirect loops.
Then I changed the http block to do an immediate rewrite if the location was = /
I have the IF statements still to handle other rewrites and then all the specific serving is done below those. It's probably just my specific configuration that results in redirect loops and errors when I attempt to handle everything as Christopher suggested or the way I originally presented in my question.
You dont need all the if statements. You should work with location satements.
This is untested and might contian errors but should work