How to force HTTPS with Nginx.

In this guide, we are going to show you how to force HTTPS on an Nginx web server.

To do this, we will need to tell Nginx to redirect all non-HTTPS traffic on port 80 to port 443.

This is because 443 is the standard TCP port for SSL.

Force HTTPS using the Nginx IF directive.

The Nginx web server allows you to use IF directives inside server blocks. As a result, we can check the $scheme variable and force a redirect if necessary.

For example:

if ($scheme = http) {
    return 301 https://$server_name$request_uri;
}

In this case, we placed the IF directive above inside the server block of my configuration file, which was located at: /etc/nginx/sites-available/default

This IF directive checks the $scheme variable to see if it is equal to http.

If the scheme is equal to http, then we simply force a 301 Redirect to the HTTPS alternative.

Using separate server blocks.

Many people believe that Nginx’s IF directive is “evil” and that you should never use it.

If you agree with this opinion, then you can create two separate server blocks.

One server block will listen on port 80 and the other server block will listen on port 443.

If a request comes in on port 80, then we will redirect it to the HTTPS version of our website.

#server block for port 80 / non-HTTPS traffic.
server {
    listen 80;
    listen [::]:80;

    server_name your_site.com;

    return 301 https://$server_name$request_uri;
}

#server block for port 443 / HTTPS traffic.
server {
    listen   443 default_server ssl;

    server_name your_site.com;

    ssl_certificate /path/to/your/ssl/cert;
    ssl_certificate_key /path/to/your/ssl/key;
}

As you can see, we created two separate server blocks.

The first block is listening for non-HTTPS requests on port 80. If our server receives a request on port 80, we “return” a 301 status code and tell Nginx to redirect to the HTTPS version of the URL.

The second block handles HTTPS requests on port 443. As you can see, we have set this to be the default server by using Nginx’s “default_server” parameter.

Basically, we are forcing HTTPS by redirecting all requests that we receive in the first server block to the second server block, which is SSL-enabled.

Once you have made your changes, you can test the Nginx configuration by using the following Linux command.

nginx -c /etc/nginx/nginx.conf -t

If your configuration passes the test, simply restart Nginx and you’re good to go.

301 Redirect.

When forcing HTTPS, it is important that you use a 301 Redirect.

A 301 Redirect will tell search engines that we have permanently moved the resource to a new URL.

As a result, your new HTTPS-enabled pages will replace your old URLs, and you will avoid any loss in rankings.

If you fail to use a 301 Redirect, search engines may penalize you for duplicate content.

See also.