About Domain Redirection to WWW or Non-WWW

To redirect non-www requests to www, use this Nginx configuration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
server {
    listen 443 ssl;
    server_name example.com www.example.com;
    charset utf-8;

    if ($host ~ ^(?!www\.)(?<domain>.+)$) {
        return 301 $scheme://www.$domain$request_uri;
    }

    # SSL certificate and other directives...

    root /var/www/html;
    index index.html;
}

server{
    listen 80;
    server_name example.com www.example.com;

    location /.well-known/acme-challenge {
        root /var/www/letsencrypt;
        try_files $uri $uri/ =404;
    }

    location / {
        return 301 https://$server_name$request_uri;
    }
}

To redirect from www to non-www, replace the condition to this one:

1
2
3
if ($host ~ ^www\.(?<domain>.+)$) {
    return 301 $scheme://$domain$request_uri;
}

Tips and Tricks Dev Ops nginx SSL