nginx and try_files: try named location with rewrites before fallback

Bretticus asked:

I’m attempting a website cut-over. We want to preserve our external links by using 301 redirects. I have a lengthy list of redirects in a named location that resembles:

location @redirects {       
    rewrite ^/path/one.html$ http://www.ourdomain.tld/one-but-different permanent;
    rewrite ^/path/two.html$ http://www.ourdomain.tld/two-but-different permanent;
    rewrite ^/path/three.html$ http://www.ourdomain.tld/three-but-different permanent;
    rewrite ^/path/four.html$ http://www.ourdomain.tld/four-but-different permanent;
}

(please note that even though it appears that my example shows a pattern, no pattern exists. In other words they are one-to-one redirects.)

I have a CMS web application that I’m using the following try_files statement currently (which has been working all along for falling back to the index.php script):

location / {
    try_files $uri $uri/ /index.php;
}

Now I’m attempting to use try_files to “look at” the redirects named location and processing the rewrite BEFORE falling back to index.php. Like this:

location / {
    try_files @redirects $uri $uri/ /index.php;
}

However, the fallback is being triggered each time as the CMS is handling 404’s. In other words, if I try http://www.ourdomain.tld/path/one.html, I get the 404 page for my CMS instead of a redirect! Is it possible to “try” a named location first or does the named location have to be the fallback?

I’m sure I’m doing this wrong. However, can someone point me in the right direction?

nginx/1.2.4

Thanks!

My answer:


Another way you can do this is with a map.

An example; off the top of my head so check for syntax errors first…:

map $uri $new {
  /path/one.html http://www.example.com/new_path_one;
  /path/two.html http://www.example.com/new_path_two;
}

server {
  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.