How to redirect non-WWW to WWW using Nginx

As you’ll often see on the internet websites usually point domain.com and www.domain.com to the same location. For smaller sites this generally doesn’t present an issue. However, when you’re trying to get properly indexed on Google you don’t want to do this because it would actually see these as two different sites.

The fix to this is to redirect any requests for domain.com to www.domain.com. Google is setup to handle this so that it will then only index www.domain.com. To set this up in Nginx it’s relatively simple. Let’s say we’re starting with the following configuration.

server {
        listen 80;
        server_name domain.com www.domain.com;
        root /var/www;
}

As it stands this one server block is configured to handle the requests for both domain.com and www.domain.com. In order to redirect domain.com to www.domain.com we need to separate them into two server blocks. Our new configuration will look like this.

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

server {
        listen 80;
        server_name www.domain.com;
        root /var/www;
}

We can see now that the second block still handles the serving of www.domain.com. But the first block now catches all the requests for domain.com and redirects them to www.domain.com where they will be caught by the second block and the content will be served. Once you’ve setup your configuration like this and restarted Nginx, all users will now end up at the www.domain.com.