0

I've got a working nginx rewrite for a location, but in the case of a specific request I want to rewrite to a different location.

location /api {
    if (!-e $request_filename){
        rewrite "^/api/.{2}\.zip" /api/general.zip last; break;
        rewrite ^/api/(.*)$ /api/router.php?rest_data=$1 last; break;
     }
}

So if someone requests /api/uk.zip then it downloads fine, but /api/fr.zip doesn't exist, so it should redirect to /api/general.zip

I've tried 2 location blocks, I get a duplicate location error, and I've tried using 2 if statements, but the second one gets ignored.

If the request is for something else, like /api/events then it should forward to the router page.

Pete
  • 283
  • 1
  • 5
  • 19
  • Ok I fixed it, that works fine except I need to wrap the first regex in double quotes, due to the curly braces `{}` in the expression. Pointed out to me from this SO question: http://stackoverflow.com/questions/14684463/curly-braces-and-from-apache-to-nginx-rewrite-rules – Pete Jan 22 '14 at 17:23
  • Scrap that, there was a syntax error which is now fixed but I still can't get 2 rewrite rules to work, it just listens to the first rule – Pete Jan 22 '14 at 17:37
  • Is it valid to use both last; break; at the end of a rewrite directive? – Russell Shingleton Jan 22 '14 at 18:01
  • I'm new to nginx, I took over from someone elses config, it seems to work so I can't really comment beyond that – Pete Jan 22 '14 at 18:15

1 Answers1

1

If-Is-Evil, avoid using if. You're a starter on nginx and maybe you didn't saw that before (check this guide for a good start). But really, avoid if. And the solution is usually try_files instead.

In your case a unique try_file cannot be used, because you need to apply a special treatment if the zip file is a two character one. But with two locations it should work. Something like that (untested):

location ^~ "/api/([0-9a-zA-Z]{2}).zip"  {
    try_files $uri /api/general.zip;
}
location ^~ "/api/(.*)" {
    try_files $uri $uri/ /api/router.php?rest_data=$1;
}
regilero
  • 1,470
  • 1
  • 9
  • 14
  • That looks about right, I ended up doing something similar, but is your answer missing a closing bracket? – Pete Jan 25 '14 at 14:23