Nginx – rewrite http to https with ngnix behind load balancer

load balancingnginx

I'm using a Rackspace load balancer which enables me to set up my ssl key/pem inside of the admin panel. Everything works fine, I can use both http and https protocols. But if I try to redirect http to https using:

server{
  listen *:80;
  server_name mydomain.com www.mydomain.com; 
  rewrite ^ https://mydomain.com$request_uri? permanent;

…I get a redirect loop. I realize I'm not listening to port 443 but that's because the load balancer handled that for me. I also tried wrapping the rewrite in if ($scheme ~* http){to no avail.

The other part of my question is that I'd like to remove www from the url, can I do this with a single rewrite? Shouldn't the above rewrite take care of this as well?

Thanks for your help!

Best Answer

sciurus is correct in that Rackspace's Cloud Load Balancers set the X-Forwarded-Proto to https when SSL is offloaded at the load balancer. In order to avoid a redirect loop in nginx, you should be able to add the following to the location section in the vhost configuration:

if ($http_x_forwarded_proto = "http") {
            rewrite  ^/(.*)$  https://mydomain.com/$1 permanent;
}

This should avoid the infinite redirect loop while redirecting non-https requests to https.