Redirect HTTP to HTTPS on Nginx

This post assumes that you have your app running and are using Nginx as the reverse proxy for your web app/server.

Technologies

  • Nginx

Usage

Separate Servers
server {
       listen         80;
       server_name    example.com;
       return         301 https://[server_name][request_uri];
}

server {
       listen         443 ssl;
       server_name    example.com;
       ...
}
Concatenated Servers
server {
       listen 80;
       listen 443 ssl;
       ....

       if ($scheme != "https") {
        return 301 https://[server_name][request_uri];
       }
       ....
}

 

Simply put, you listen on both port 80 (HTTP) and port 443 (HTTPS) to expose both HTTP and HTTPS for your web application/server, then you returnĀ 301 https://[host_ip][request_url] on port 80 which redirects all traffic to HTTPS.

After you add this to the nginx.conf file, make sure to restart the nginx service

sudo service nginx reload

and see if it takes effect.