301 redirect with nginx 03 Jul 2010
Tags: nginx, 301 redirect, www domain

If you need to redirect your urls to use the www domain, then it's easy to do a 301 redirect if you're using nginx

plain
server {
  listen 80;
  server_name example.com www.example.com;
  root /var/www/example.com/public;
  passenger_enabled on;
  rails_env production;

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

One of the important reasons why you need to do this is analytics. Google, for example, sees www.example.com and example.com as two different sites. So to have a more accurate report on your site traffic, use a 301 redirect.

EDIT:

Apparently, this is not the best way to write a 301 redirect in nginx. Have a look at this page to see how to do this elegantly.