How to Redirect HTTP Requests to HTTPS on Nginx?

02-02-2024 02:16:38

To achieve this, one must prepare a cloud server running Nginx and have an SSL certificate properly deployed for the domain. This guide explains how to redirect HTTP requests to HTTPS.

The first step involves locating the Nginx configuration file. By default, the path for the Nginx configuration file is: /etc/nginx/nginx.conf. For web servers hosting multiple websites, it's common to place each website's configuration file in the /etc/nginx/conf.d/ directory, with one configuration file per website. For instance, the configuration file path for the website example.com would be: /etc/nginx/conf.d/example.conf.

The fundamental steps to redirect HTTP to HTTPS include adding a line of code similar to the following in the section listening on port 80.

return 301 https://example.com$request_uri;

Additionally, add code to listen on port 443 and configure the SSL certificate. Below is a complete configuration example where accessing http://example.com and http://www.example.com will redirect to https://example.com.

http {
    server {
        listen 80;
        server_name example.com www.example.com;
        # Redirect all port 80 (HTTP) requests to port 443 (HTTPS).
        return 301 https://example.com$request_uri;
    }

    server {
        listen 443 ssl;
        server_name example.com;
        ssl_certificate     /path/to/cert-crt.crt;
        ssl_certificate_key /path/to/cert-key.key;
        # all other site settings go here (e.g. ssl, logs, site root)
    }
}