If you have your website up and running, but Google (or any other analytics tool) whines about the site being reachable via www.domain.com and domain.com you will find this tutorial come in handy ;-)

Prerequisites

You (of course) should have installed Nginx. Howto?

Configure Nginx Redirect

In order to do the 301 redirect, we must add a server block that points to our original block.

Open nginx configuration file:

sudo nano /etc/nginx/sites-enabled/default

Option 1: Redirect www to non-www

If you want to redirect from www to non-www domain, use this config:

server {
    listen 80;
    server_name www.domain.com;
    return 301 $scheme://domain.com $request_uri;
}

To put the changes into effect, restart Nginx:

sudo service nginx restart

Option 2: Redirect non-www to www

If you want redirect users from non-www to www, add this:

server {
    listen 80;
    server_name domain.com;
    return 301 $scheme://www.domain.com $request_uri;
}

To put the changes into effect, restart Nginx:

sudo service nginx restart

 

Test?

curl -I http://(your-chosen-www-or-non-www).domain.com

You should get a 301 Moved Permanently response, that shows the non-www redirect location, like this: