How to redirect HTTP to HTTPS with nginx?

Published on Aug. 22, 2023, 12:19 p.m.

To redirect HTTP to HTTPS with nginx, you can add a new server block for HTTP that listens on port 80 and redirects to the corresponding HTTPS URL. Here are the general steps:

  1. Edit your nginx configuration file and locate the server block that serves HTTP requests on port 80.
  2. Add a new server block that listens on port 80 and redirects to the HTTPS URL. You can use the return directive to perform a 301 redirect, which is a permanent redirect that tells search engines to update their indexes with the new URL.
  3. In the new server block, specify the location of the HTTPS URL.

Here’s an example of what the new server block might look like:

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

Note that you should replace example.com with your own domain name, and customize the redirect URL as needed.

After you’ve made changes to the nginx configuration file, you need to reload the nginx service to apply the changes.

Tags: