Web Server

nginx www Redirect

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.

[cc lang=”apache”]
server
{
server_name www.domain.com;
rewrite ^(.*) http://domain.com$1 permanent;
}
[/cc]

Redirect non www to www

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

[cc lang=”apache”]
server
{
server_name domain.com;
rewrite ^(.*) http://www.domain.com$1 permanent;
}
[/cc]

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

[cc lang=”apache”]
server
{
server_name old_domain.com;
rewrite ^(.*) http://new_domain.com$1 permanent;
}
[/cc]

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.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *