user1429605
user1429605

Reputation: 31

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.

Upvotes: 1

Views: 3341

Answers (1)

Sébastien Renauld
Sébastien Renauld

Reputation: 19662

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!

Upvotes: 1

Related Questions