How to redirect www to non-www with Nginx / Ubuntu / DigitalOcean

Coming from the land of cPanel / Apache, managing my own droplet on DigitalOcean was a real adventure. Some things were easy to understand, some were harder and some made me look like the amateur I am.

I managed to add multiple domains and subdomains with success during the past two years so I thought I got at least the basics going. But imagine my surprise when I discovered none of the domains hosted had the www version available.

DigitalOcean has a comprehensive tutorial on the subject, How To Redirect www to Non-www with Nginx on Ubuntu 14.04 but it was lacking some clarifications.

There's no point in rewriting my own version of the same tutorial, so just head over there to learn more. However, I will give you a shorter, TL;DR version, covering some aspects they missed.

First thing, head over to the control panel's Domains section and create a new A record for your domain. The name will be www and the IP address the same.

The second part will have you configure Nginx. If you only have one domain, you should edit /etc/nginx/sites-enabled/default. In my case, since I have more than one, I had to edit a /etc/nginx/sites-enabled/domain.conf for each domain I needed this change.

The DigitalOcean tutorial wasn't very clear for this part. The trick is you have to add the following block besides the old one. Since I already had a server { (...) } I figured I had to insert the new lines alongside the old ones but no, I was dead wrong.

The block of code in question is this one:

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

According to a StackOverflow answer to the question Nginx no-www to www and www to no-www, you should also include the listen command.

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

Here's what one of mine's looks likes, for example:

And now comes the hard part... just kidding! All that's left to do is to ssh into your droplet and restart nginx with sudo service nginx restart (if no terminal is available, you can access the console from inside the Droplets menu).

You will get an [OK] message if everything is ok or [fail] if you botched something up, like a typo inside the .conf file.

And last but not least, by far the most important advice: if this does not work give it some time!.

After configuring my first domain and still running into the "server DNS address could not be found." error I was desperately searching the net for answers only to check again and see everything was up and running after a couple of minutes. It was a DNS thing most likely :)

So there you have it, you can now enjoy your new site with a new www added flavour!