Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
share|improve this question
up vote 3 down vote accepted

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;
share|improve this answer
Take a look at that space between ( and {, missing that cost me an hour with unknown variable error – Adarsha Mar 11 at 8:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.