简体   繁体   English

使用正则表达式检查Nginx上是否存在文件

[英]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: 我正在尝试将一些htaccess文件转换为Nginx vhost配置,而我遇到了麻烦:

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. 如您所见,此条件使用正则表达式检查文件是否存在,以通过输入的URL动态生成文件名。

The following nginx directive do the rewrite correctly but doesn't checks for the file bofore: 以下nginx指令可以正确重写,但不会检查文件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. try_files指令将尝试在$ uri然后在$ uri /处查找文件,其中$ uri是URL中指定的路径。 Failing this, it will then go to the @what_to_do location block, where the rewrite is. 如果失败,它将进入重写所在的@what_to_do位置块。

Bonus point: this also allows you to neatly separate your rewrite rules from the rest of the server config! 优点:这还使您可以将重写规则与其余服务器配置巧妙地区分开!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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