Allan & Steve are the chubby founders of LessEverything. This is their blog, hear them rant, praise, give advice and talk about Just Stuff, Less Accounting, Lovd by Less, More Honey, Events, Less Memories, Code, Business, Design, Marketing
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. Nginx makes it really easy to do.
Just add this to your server{} block:
if ($host != 'your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.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.your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
Sorry, comments are closed for this article.
Nice post and it’s worth noting that those redirects should always be 301s unless you know what you’re getting into.
@she-ra
Good point. Actually, the word “permanent” in the config snippet tells Nginx to do a 301, not a 302.
steve
I just stick it in its own server block..
server { listen 80; server_name www.oftengloomy.com; rewrite ^/(.*) http://oftengloomy.com permanent; }
@Brennan,
That’s a good idea.
I prefer Brennan’s way, and used it on several sites.
@ashchan,
Thanks for your comment. :)
steve
Thanks for the post. Igor Sysoev states here that the $1 can be replaced by $uri so that the rewrite could be written as “rewrite ^ http://your_domain.com/$uri permanent;”.
@Ronnie,
Thanks for the tip! :)
A small correction to my previous comment: There should be no slash before $uri. The rewrite line should be “rewrite ^ http://your_domain.com$uri permanent;”. The previous line works, but it will produce a double slash because $uri contains a leading slash.
Does nginx support regex on this statement? What if I have a few vhosts and want to redirect it just once, instead of multiple times? Is it possible?
@Hendry,
It does support regex. I’m not sure I understand your second question, but you may have multiple if/redirect statements.
steve