Remove the "www" from a URL with Nginx

Dec 27, 2014 Nginx

In moving away from the old-school standard of prefixing our root domains with www, it's nice to still allow traffic with and without the www in the domain name. For example, you can get to this site by going to cobwwweb.com, but you can also get here by going to www.cobwwweb.com.

You may have noticed that if you try the second URL (the one with the www), it gets removed from the address bar. It is ideal for SEO (search engine optimization) purposes that you choose one (with or without www) and stick with it by redirecting traffic from the other domain to your main domain.

With Nginx as your web server, the proper way of doing so is to perform a 301 redirect in a separate server directive. Use the following in addition to your main server directive.

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

Note: It's okay to have multiple directives in one file, but it's good to keep the directives separate from one another.

In this case, we're getting rid of the www and considering yourdomain.com to be your main domain. You could just as easily do the reverse, like so:

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

Did you learn something or find this article interesting?

If so, why not