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

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 {
  return 301 $scheme://$request_uri;

# 301 redirect list
map $uri $new {

server {
  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 any other answers on Server Fault.

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