简体   繁体   中英

Check if file exists on Nginx using regex

I'm trying to translate some htaccess files to Nginx vhost configuration, and i'm having trouble with this:

RewriteCond %{DOCUMENT_ROOT}/img/id_$1_$2 -f
RewriteRule ^id/(.+)/(.+)$ img/id_$1_$2 [NC,L]

As you can see, this condition checks if a file exists using some regex to generate filename dynamically by the URL entered.

The following nginx directive do the rewrite correctly but doesn't checks for the file bofore:

rewrite ^/id/(.+)/(.+)$ /img/id_$1_$2 break;

I just want to do this rewrite if the file really exists, and if not another rewrite will happen.

All ideas may help. Thanks a lot.

try_files $uri $uri/ @what_to_do;

From there, define a new location as follows:

location @what_to_do {
    rewrite ^/id/(.+)/(.+)$ /img/id_$1_$2 break;
}

The try_files directive will attempt to find files at $uri and then at $uri/ , where $uri is the path specified in the URL. Failing this, it will then go to the @what_to_do location block, where the rewrite is.

Bonus point: this also allows you to neatly separate your rewrite rules from the rest of the server config!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM