/nginx, redirect, domain

Using nginx redirect www to non-www domain

Having your site configured on nginx with

server_name example.com www.example.com;

is a good thing as it'll allow your visitors to access your site on both example.com and www.example.com, but they'll stay on the version of the domain they used to access your site in the first place. In your analytics, you may start seeing traffic separated into example.com and www.example.com which definitely does not help you get a clear view of your visitors. It's good practice to decide on one version of the domain and stick to it. I prefer the non-www version, but it's entirely up to you.

Redirect www to non-www

To redirect all traffic from www.example.com to just plain example.com, add another server {} block to your nginx config file with just two lines:

# new block
server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}
# your normal config
server {
    ...
    server_name example.com; # notice, this has just the non-www version
    ...
}

Restart nginx to apply above changes

sudo systemctl restart nginx

Redirect non-www to www

To redirect your users from non-www to a www version of your domain add below:

# new block
server {
    server_name example.com;
    return 301 $scheme://www.example.com$request_uri;
}
# your normal config
server {
    ...
    server_name www.example.com;
    ...
}

Restart nginx to apply above changes

sudo systemctl restart nginx

Conclusion

That's it. Your users will now be able to access your site on both www and non-www versions and will be permanently redirected to one version you chose.