Nginx: Redirect www to non-www

July 4, 2009 by Mark  
Filed under Tips & Tricks

Method 1
Open your nginx.conf and add the following configuration inside your server {} configuration.

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


Make sure you change domain.com with your own domain name and save the configuration file before you restart nginx.

Method 2
As usual, open nginx.conf and add the following configuration to the file. Don’t forget to change domain.com with your own domain.

server {
    server_name  www.domain.com;
    rewrite ^(.*) http://domain.com$1 permanent;
}

server {
    server_name  domain.com;
    Put all other web server configuration here
}

To make the change take effect you have to save the configuration file and restart nginx. Now when visitor type www.domain.com on their browser address bar it will redirect to domain.com.

Both method are simple and easy. Adding only a few lines and wah la, the jobs is done.

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!