Nginx map module 301 redirecting

Reinier Korth asked:

I’ve rebuild my website in Ruby on Rails and now I want to 301 redirect a lot of old urls using Nginx’s http://wiki.nginx.org/HttpMapModule

For some reason I can’t get it to work. It works fine without the rewrite ^ $new permanent; line.

Does anyone see what I’m missing?

This my nginx.conf:

server {
  server_name example.com;
  return 301 $scheme://www.example.com$request_uri;
}

# 301 redirect list
map $uri $new {
  /test123 http://www.example.com/test123;
  /bla http://www.example.com/bladiebla;
}

server {
  server_name www.example.com;
  rewrite ^ $new permanent;
  root example/public;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn-<%= application %>;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

My answer:


This is probably failing because you’re trying to redirect all requests, whether they matched something in the map or not.

To prevent this, check to see if there was a match first.

if ($new) {
    return 301 $new;
}

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.