rewrite http to https with ngnix behind load balancer

Solution 1:

By using nginx's built-in server variables $request_uri and $server_name you can do this without using regular expressions at all. Add the following to your server's location block and you're done:

if ($http_x_forwarded_proto = "http") {
    return 301 https://$server_name$request_uri;

This assumes your load balancer is sending the $http_x_forwarded_proto header along with the request to your backend instance(s). Other common headers include $http_x_forwarded_scheme and also just $scheme.

More information can be found in the nginx Pitfalls and Common Mistakes documentation :

Solution 2:

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  ^/(.*)$$1 permanent;

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