May 17, 2018

Redirect www to non-www subdomain

^ Ad space to help offset hosting costs :D

Nginx's server_name can take multiple hostnames. This is useful for serving sites with different hostname with the same code-base, allowing wildcard subdomains, or for serving the www subdomain as well as the root domain.

However, we often want to redirect a www subdomain to a non-www subdomain (or visa-versa!) to keep the domain in use consistent.

That's easily achievable in Nginx:

server {
    server_name foo.com www.foo.com;
}

########

server {
    listen 80;
    listen 443 ssl;

    include ssl.conf; # SSL config options

    server_name www.foo.com;
    return 301 $scheme://foo.com$requests_uri;
}

server {
    listen 80 default_server;
    listen 443 ssl;

    include ssl.conf; # SSL config options

    server_name foo.com;
    location / {
        try_files $uri $uri/ =404;
    }
}

Here we listen for www.foo.com requests and redirect any to the root domain foo.com. We have them in separate server blocks to avoid using most costly if conditionals within our main configuration.

We redirect with a 301, keeping the same $scheme (http vs https) and passing along the $request_uri that was used.

SSL

Don't forget to handle SSL (if you're using a certificate!) for the domain you are redirecting! If you only listened for www.foo.com on port 80, https requests on port 443 would not get any response.

For the sake of brevity, I've tucked away the SSL configuration into a ssl.conf file which in this example would likely be located at /etc/nginx/ssl.conf and would contain the needed configuration to point Nginx to a certificate, it's private key, and any other options such as ciphers and dhparams.

All Topics