简体   繁体   English

如何在该位置使用Nginx Regexp

[英]How to use Nginx Regexp in the location

The web project have static content into the some /content/img folder. Web项目将静态内容放入some / content / img文件夹中。 The url rule is: /img/{some md5} but location in the folder: /content/img/{The first two digits}/ 网址规则为:/ img / {some md5}但文件夹中的位置:/ content / img / {前两位数}} /

Example

url:      example.com/img/fe5afe0482195afff9390692a6cc23e1
location: /www/myproject/content/img/fe/fe5afe0482195afff9390692a6cc23e1

This nginx location is correct but lot not security (the symbol point is not good in regexp): 这个nginx位置是正确的但很多不安全(符号点在regexp中不好):

        location ~ /img/(..)(.+)$ {
               alias $project_home/content/img/$1/$1$2;
               add_header Content-Type image/jpg;
         }

The next location is more correct, but not work: 下一个位置更正确,但不起作用:

        location ~ /img/([0-9a-f]\{2\})([0-9a-f]+)$ {
               alias $project_home/content/img/$1/$1$2;
               add_header Content-Type image/jpg;
         }

Help me find error for more correct nginx location. 帮我找到更正确的nginx位置的错误。

Escaping the braces in the limiting quantifiers is necessary in POSIX BRE patterns, and NGINX does not use that regex flavor. 在POSIX BRE模式中,必须转义限制量词中的括号,NGINX不使用该正则表达式。 Here, you should not escape the limiting quantifier braces, but you need to tell NGINX that you pass the braces as a part of the regex pattern string. 在这里,你不应该逃避限制量词括号,但你需要告诉NGINX你将大括号作为正则表达式模式字符串的一部分。

Thus, you need to enclose the whole pattern with double quotes: 因此,您需要用双引号括起整个模式:

Use 采用

location ~ "/img/([0-9a-fA-F]{2})([0-9a-fA-F]+)$"

Here is a regex demo . 这是一个正则表达式演示

Note that in the current scenario, you can just repeat the subpattern: 请注意,在当前场景中,您只需重复子模式:

 /img/([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F]+)$
      ^^^^^^^^^^^^^^^^^^^^^^^^

I got it working putting double-quotes around the location part like this: 我得到它的工作在这个位置部分周围加双引号:

location ~ "/img/([0-9a-f]{2})([0-9a-f]+)$"

the reason is that Nginx uses curly brackets to define config blocks so it thinks is opening a location block. 原因是Nginx使用大括号来定义配置块,因此它认为是打开一个位置块。

Source 资源

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

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