5

I have the following NGINX rewrite rule which works great for a PHP script installed in a subfolder:

location /subfolder/ {
  if (!-e $request_filename){
    rewrite ^/subfolder/(.*) /subfolder/index.php?do=/$1;
  }
}

but Nginx wiki says using "if" is evil http://wiki.nginx.org/IfIsEvil so I tried the following

location /subfolder/ {
    try_files $uri $uri/ /subfolder/index.php?$args;
}

but it doesn't work to replace the one above, although it works for WordPress and most of the PHP scripts. If there a way to translate it to use "try_files"?

Thank you!

user702300
  • 1,211
  • 5
  • 22
  • 32

1 Answers1

10

You want to do the rewrite only if the file doesn't exist, use it as a named location for the fall back in try_files

location /subfolder {
    try_files $uri $uri/ @rewrite;
}

location @rewrite {
    rewrite ^/subfolder/(.*) /subfolder/index.php?do=/$1;
}
VBart
  • 14,714
  • 4
  • 45
  • 49
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
  • That didn't work and Nginx won't start with the following error message: [emerg] unknown directive "$uri" in /etc/nginx/nginx.conf:2252 – user702300 Nov 16 '13 at 17:53
  • And it was referring to the following line: $uri $uri/ @rewrite; – user702300 Nov 16 '13 at 17:55
  • Adding try_files also didn't help: try_files $uri $uri/ @rewrite; it generates the following error: unknown directive "@rewrite" in /etc/nginx/nginx.conf:2254 – user702300 Nov 16 '13 at 17:58
  • what nginx version do you have ?, and yea i forgot to write `try_files` – Mohammad AbuShady Nov 16 '13 at 20:43
  • My Nginx version is 1.0.10 – user702300 Nov 16 '13 at 23:32
  • Thanks for the tips, I've upgraded to Nginx 1.4.x. I had to add "location" in front of "@rewrite {" line and it worked. Thank you very much! – user702300 Nov 16 '13 at 23:44
  • ok, idk why but apparently I was having a slow moment, 2 mistakes in the same answer, glad you figured it out, and thanks @VBart for fixing the answer. – Mohammad AbuShady Nov 17 '13 at 05:28
  • bro you solved my great pain because i was living nginx just because i doesn't find any better way for rewriting urls . Can you suggest a way to rewrite only non integral requests like avoiding ( /subfolder/1 or /subfolder/2 or /subfolder/3 ) – Ravinder Payal Oct 15 '15 at 14:16