with nginx having the base url rewrite to https

Posted by jchysk on Server Fault See other posts from Server Fault or by jchysk
Published on 2012-09-30T09:41:52Z Indexed on 2012/09/30 15:39 UTC
Read the original article Hit count: 323

Filed under:
|
|
|

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?

© Server Fault or respective owner

Related posts about nginx

Related posts about ssl