Nginx SSL redirect without if

Xeli asked:

In this question: rewrite http to https with ngnix behind load balancer

the question is how to force SSL for nginx servers behind a loadbalancer. The problem with this setup is that the loadbalancer handles SSL and has a non SSL connection with the webservers/nodes.

So it looks at the http-x-forwarded-proto header. The accepted answer works fine except that it uses an if like so:

if ($http_x_forwarded_proto = "http") {
            rewrite  ^/(.*)$$1 permanent;

which is evil:

Is there a better way to do this without an if?

One possible solution would be to force ssl at the loadbalancer, but this loadbalancer is managed by our hoster, which makes changes more tedious, im hoping for an answer which doesn require changes to the loadbalancer

My answer:

Since you have nginx behind an SSL-terminating load balancer, I don’t think it will be easy for you to avoid using if. But not all is lost.

To be “not evil” you can replace rewrite permanent with return, one of the safe things you can do with if.

    return 301 https://$http_host$request_uri;

This will simply reconstruct the URL with https, and everything else exactly as given.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.