Last Updated: February 25, 2016
·
1.348K
· davefp

Redirect an entire site to secure URLs using nginx

In your site config, you'll need two server blocks.

The first listens for your site on port 80 and returns a 301 (Permanently Moved) response with the exact same URL as the reqeust prefixed with https instead of http

The second is where you put all your actual site info, and it listens on 443 like any other secure site.

If a request comes in on port 80 it'll bounce off the first block and the subsequent request (assuming the redirect is followed correctly) will hit the second as planned. The 301 has the added benefit of being cached client-side which will prevent subsequent requests from the same person from hitting the insecure site.

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;
        ...
}

Lots of other solutions I saw wanted to do complex conditional URL rewrites. I found the above solution is much more elegant.