Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Nginx rewrite from "if" to "try_files"

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!

like image 368
user702300 Avatar asked Nov 15 '13 22:11

user702300


1 Answers

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;
}
like image 152
Mohammad AbuShady Avatar answered Sep 30 '22 09:09

Mohammad AbuShady