Nginx redirects

  1. HTTP to HTTPS
    1. Where does it go?
    2. Where in the file should I put this?
  2. WWW to non-WWW
    1. Where does it go?
    2. Where in the file should I put this?

This is a list of the redirects code snippets that works for me.

  1. HTTP to HTTPS
    1. Where does it go?
    2. Where in the file should I put this?
  2. WWW to non-WWW
    1. Where does it go?
    2. Where in the file should I put this?

HTTP to HTTPS

Code for redirecting all HTTP requests to HTTPS:

1
2
3
if ($scheme = http) {
rewrite ^/(?!.well-known)(.*) https://MYWEBSITE.COM/$1 break;
}

Where does it go?

It goes into the domain specific config file, e.g.:

1
/etc/nginx/sites-available/MYWEBSITE.COM.conf

Where in the file should I put this?

Inside the main server{} code group, e.g.:

1
2
3
4
5
6
7
8
9
server {
server_name MYWEBSITE.COM www.MYWEBSITE.COM;
# Rest of file content goes here
# ...
# ...
if ($scheme = http) {
rewrite ^/(?!.well-known)(.*) https://MYWEBSITE.COM/$1 break;
}
}

WWW to non-WWW

Code to redirect all WWW requests to the non-WWW URL version:

1
2
3
4
server {
server_name www.MYWEBSITE.COM;
return 301 $scheme://MYWEBSITE.COM$request_uri;
}

Where does it go?

It goes into the domain specific config file, e.g.:

1
/etc/nginx/sites-available/MYWEBSITE.COM.conf

Where in the file should I put this?

You need to create another server{} group before the main one:

1
2
3
4
5
6
7
8
9
10
11
server {
server_name www.MYWEBSITE.COM;
return 301 $scheme://MYWEBSITE.COM$request_uri;
}

server {
server_name MYWEBSITE.COM;
# Original config content
# ...
# ...
}

notice that the main server{} group only needs the non-WWW version of the URL as server_name

dark