Some biographical details here.


Published:

Redirecting www to non-www host

Earlier this evening I was browsing the Ghost forums when I read a thread about individuals looking to redirect their www.whatever.com host to whatever.com instead.

The Proper Way in Nginx

The most appropriate way to redirect your www to non-www host is to use the server {} block within your Nginx site configuration (virtual host file).

As an actual example, I will share how I am redirecting www.justinshattuck.com to justinshattuck.com on this very blog.

Redirect www to non-www:

My virtual host configuration file exists in the path /etc/nginx/sites/js

server {  
    ...
    server_name justinshattuck.com
    ...
}

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

The first server { ... } block informs Nginx to listen for justinshattuck.com and the second server { ... } block informs Nginx to listen for www.justinshattuck.com and use return to deliver the visitor to justinshattuck.com with the original request intact.

Redirect non-www to www:

If you are looking to redirect non-www host to www, you would use the same configuration above, but with the server_name entries reversed:

server {  
    ...
    server_name www.justinshattuck.com
    ...
}

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

Personally, I am not a fan of www hostnames so I scrap them as often as possible. Enjoy!