Strip the www with nginx

DNS is a pain. The internet is littered with people complaining about "naked domain" problems - where a site responds to "" but not "".

But I have the opposite problem. URLs should be nice to look at - and personally, I'm no fan of the "www." prefix. I want the address of this site to be not However; fact is, people will type "www." and I need to handle that.

Luckily this is quite easy if you're comfortable with DNS and changing a few lines in a config file.

The first thing to do is make sure both the "naked domain" and "www" subdomain are pointing to the right server. To do this set A records for both @ and www to point to your IP address.

Naked domain A record

www A record

Once these have propagated the site should be available at both "" and "".

Now, to remove the "www." and forward the user onto the correct page on the naked domain. E.g. "" to "".

To do this we need to edit the config for the nginx site; found in the directory /etc/nginx/sites-available. Here an additional server section should be added as follows.

server {
  return 301 $scheme://$request_uri;

This will 301 redirect any request prefixed with "www." to the same path on the naked domain.