Nginx – Redirect from HTTP to HTTPS with respect to the X-Forwarded-For header (SSL termination used)

httphttpsload balancingnginxredirect

I'm looking to redirect from HTTP to HTTPS. My Nginx server sits behind a load balancer which will terminate SSL for me and send all traffic (HTTP and HTTPS) to port 80. The only evidence I will have to indicate whether the original request made was HTTP or HTTPS is via the X-Forwarded-For header that is set by the load balancer. Is there a built-in, inexpensive way to handle redirection in Nginx when the original request was on HTTP? Keep in mind, I'll only have a server set up for port 80.

Best Answer

Assuming that you're guaranteeing that the X-Forwarded-For header is only set for SSL traffic ...

if ($http_x_forwarded_for) {
    return 301 https://$host$request_uri;
}

Although this is arguably something you should do at the balancer.