簡體   English   中英

如何在該位置使用Nginx Regexp

[英]How to use Nginx Regexp in the location

Web項目將靜態內容放入some / content / img文件夾中。 網址規則為:/ img / {some md5}但文件夾中的位置:/ content / img / {前兩位數}} /

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

這個nginx位置是正確的但很多不安全(符號點在regexp中不好):

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

下一個位置更正確,但不起作用:

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

幫我找到更正確的nginx位置的錯誤。

在POSIX BRE模式中,必須轉義限制量詞中的括號,NGINX不使用該正則表達式。 在這里,你不應該逃避限制量詞括號,但你需要告訴NGINX你將大括號作為正則表達式模式字符串的一部分。

因此,您需要用雙引號括起整個模式:

采用

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

這是一個正則表達式演示

請注意,在當前場景中,您只需重復子模式:

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

我得到它的工作在這個位置部分周圍加雙引號:

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

原因是Nginx使用大括號來定義配置塊,因此它認為是打開一個位置塊。

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM