Redirect non-www url to www in nginx

By | June 17, 2013

Nginx

Recently I was setting up nginx on my new server where this blog is being hosted. Nginx is very different from the more popular apache web server in many ways. It has an event driven architecture which makes it much faster and high traffic tolerant compared to apache.

In apache the redirects used to be done with instructions in the htaccess file. However in nginx there is no htaccess file and everything has to be done in the configuration file.

non www to www redirect

It is a common practice to permanently redirect non-www urls to www urls since it presents only one version of the urls and for that it is considered and seo friendly practise.

In nginx it is common to maintain a separate configuration file for each site (a.k.a domain or vhost). Each vhost is declared and identified by a server block.

Here is a quick example of how you can redirect the urls. This snippet should go into the location block.

# non-www to www redirect
if ($host !~* ^www\.)
{
	rewrite  ^/(.*)$  http://www.$host/$1  permanent;
}

$host is a variable provided by nginx. The above piece of code checks if the hostname provided in http request starts with a www or not. If not then permanently rewrite it to www prepended version.

Inside the location block it could look like this

location / {
	# First attempt to serve request as file, then
	# as directory, then fall back to displaying a 404.
	# add index.php for wordpress, wordpress is easy
	try_files $uri $uri/ /index.html /index.php;
	# Uncomment to enable naxsi on this location
	# include /etc/nginx/naxsi.rules
	
	# non-www to www redirect
	if ($host !~* ^www\.)
	{
		rewrite  ^/(.*)$  http://www.$host/$1  permanent;
	}
}

Separate server block

The above shown technique works, but could mess with other redirect rules present in sub directories or so. A much neater way to make the above redirect is by creating a separate server block. It looks like this

# redirect non-www to www
server { 
	server_name mysite.com; 
	return 301 http://www.$host$request_uri; 
}

Put this server block above the main server block for mysite.com
This code simply redirects any request for mysite.com to "www." version. Looks neat and is handled separately.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

Leave a Reply

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