user702300
user702300

Reputation: 1241

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!

Upvotes: 5

Views: 8924

Answers (1)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42799

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;
}

Upvotes: 10

Related Questions