How to configure Nginx to redirect HTTP traffic to HTTPS?

To configure Nginx to redirect HTTP traffic to HTTPS, you will need to make changes to the Nginx configuration file. Here's a step-by-step guide on how to do it:

  1. Open the Nginx configuration file. The location of the file may vary depending on your operating system but it is usually found in the /etc/nginx/ directory. The main configuration file is typically named nginx.conf.

  2. Locate the server block that handles HTTP traffic. By default, this block is usually present in the configuration file and listens on port 80. It looks something like this:

    server { listen 80; server_name example.com; ... }
  3. Inside the server block, add a new location block to handle redirection. This block should match all HTTP traffic and redirect it to HTTPS. Here's an example:

    server { listen 80; server_name example.com; location / { return 301 https://$host$request_uri; # Redirects HTTP to HTTPS } ... }

    The return 301 directive specifies a permanent HTTP redirect (301), and the https://$host$request_uri value redirects to the same host and request URI on HTTPS.

  4. Save the configuration file and exit the editor.

  5. Test the configuration for any syntax errors. Run the following command:

    nginx -t

    If there are no errors, proceed to the next step. Otherwise, fix the errors before continuing.

  6. Restart Nginx to apply the changes. Use the appropriate command for your operating system. For example:

    service nginx restart # On systemd-based systems systemctl restart nginx # On systemd-based systems (alternative) service nginx restart # On SysV init systems (e.g., Debian) /etc/init.d/nginx restart # On SysV init systems (e.g., CentOS)
  7. Verify that the redirection is working by accessing your website using HTTP (e.g., http://example.com). It should automatically redirect to HTTPS (e.g., https://example.com).

Note: Before configuring this redirect, ensure that you have a valid SSL/TLS certificate installed and properly configured to enable HTTPS.