nginx www Redirect

By Avinash

April 10, 2012Web Server1 Comment

After few days of study about the nginx I have something to write about nginx. Its a very basic things but can say a good start too. ;)

I am writing this article for redirecting non www website to www and www website to non www using nginx permanent redirection. In nginx just like apache we do not have anything like htaccess file which can be placed in webroot.

In nginx we have separate conf file for each domain we have configured and that can be editable by root users only, this is the main reason to not have nginx on shared server.

All the redirect rules can be written inside the server tag in nginx configuration file. So Let’s have a look about how we can place redirect rule for the www.

Redirect www to non www

Here is the code which you need to place in domain’s configuration file to make all URL non www.

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

Redirect non www to www

Here is the code which you need to place in domain’s configuration file to make all URL www.

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

One idea just came into mind while writing this article, We can redirect all request from one domain to another domain using nginx. Have a look at below code block for the same.

Redirect One Domain to Another

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

If you have any other better way to achieve the same the please do share here so other developers including me will come to know about the better practices for the nginx.

Share This Article

  • http://ivy.fm/ Abdullah Cetin CAVDAR

    NGINX is gaining popularity. According to the Netcraft’s survey in January 2012 “In terms of Active Sites, nginx gained 1.9M which resulted in it overtaking Microsoft to have the second largest number of Active Sites (22.2M).” It rocks.

    See details here: http://news.netcraft.com/archives/2012/01/03/january-2012-web-server-survey.html

    Thx for the post. :)