Redirect from www to non-www using Nginx

Written by on Apr 9 2008

Let’s say you want to redirect users from the www sub-domain of your website to direct access via the non-sub-domain url.

Just add this to your server{} block:

if ($host != ‘yourdomain.com’ ) { rewrite ^/(.*)$ http://yourdomain.com/$1 permanent; }

This actually will redirect any sub-domain to the non-sub-domain url. But what if, like Less Accounting, your site has user accounts for sub-domains or you have other valid sub-domains, but you still want to get users away from www?

Just add this to your server{} block:

if ($host = ‘www.yourdomain.com’ ) { rewrite ^/(.*)$ http://yourdomain.com/$1 permanent; }

 

Meet
Steven

Hi I'm Steven,

I wrote the article you're reading... I lead the developers, write music, used to race motorcycles, and help clients find the right features to build on their product.

Get Blog Updates