301 redirect with more than 1 alias in nginx 11 Jul 2011
Tags: nginx, config

Usually, companies acquire multiple domains and point them to one application. In these cases, the company would want to use a 301 redirect to change the url to the one they want indexed by search engines.

In nginx, you can do a 301 redirect by following my other post. It would've been easy if "if" blocks in nginx support conditional operators like || or && (in most programming languages).

To get around this, we use the set command to set a value to a variable, and set that variable's value if the host matches one of the alias. To better illustrate, suppose we're given 4 domains:

plain
www.example.com
example.com
www.example.org
example.org

If the domain we want indexed by search engines is www.example.com, then our config file should look like

plain
server {
  listen 80; 
  server_name www.example.com example.com www.example.org example.org;

  set $my_var 0;
  if ($host = 'example.com') {set $my_var 1;} 
  if ($host = 'example.org') {set $my_var 1;}
  if ($host = 'www.example.org') {set $my_var 1;} 

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