Skip to content

How to Redirect HTTP to HTTPS in Nginx

In most cases, you can locate the file in the /etc/nginx/sites-available directory. If not found, search for it here: /etc/nginx/nginx.conf, /usr/local/nginx/conf, or /usr/local/etc/nginx.

Open your Nginx config file as shown below.

sudo vi /etc/nginx/sites-available/default

Add or update the server block similar to the below sample, to match your requirements

server {
    listen 80 default_server;
    server_name _;

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

Once you are finished editing, save the file and exit. Then, restart the Nginx service with the following command:

sudo service nginx restart

Here is a breakdown of the commands:

  • Listen 80: This instructs the system to catch all HTTP traffic on Port 80
  • Server_name _;: This will match any hostname
  • Return 301: This tells the browser (and search engines) that this is a permanent redirect
  • https://$host$request_uri: This is a short code to specify the HTTPS version of whatever the user has typed

Now all incoming requests will be routed to the HTTPS version.

Comments are closed, but trackbacks and pingbacks are open.