如何在 location 中使用 Nginx Regexp

How to use Nginx Regexp in the location

Web 项目将静态内容放入某些 /content/img 文件夹中。 url 规则是:/img/{some md5} 但在文件夹中的位置:/content/img/{前两位}/

示例

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

这个 nginx 位置是正确的但很多不安全(正则表达式中的符号点不好):

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

下一个位置更正确,但行不通:

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

帮我找错更正确的nginx位置。

在 POSIX BRE 模式中需要转义限制量词中的大括号,而 NGINX 不使用那种正则表达式风格。在这里,您不应该转义限制量词大括号,但您需要告诉 NGINX 您将大括号作为正则表达式模式字符串的一部分传递。

因此,您需要用双引号将整个模式括起来:

使用

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

这里是regex demo.

请注意,在当前情况下,您可以重复子模式:

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

我把 double-quotes 放在位置部分周围,如下所示:

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

原因是 Nginx 使用大括号来定义配置块,因此它认为打开了一个位置块。

Source