【问题标题】:PCRE ^~ symbol in nginxnginx 中的 PCRE ^~ 符号
【发布时间】:2017-06-29 23:28:55
【问题描述】:

我有这个 nginx 位置块(来自https://munin.readthedocs.io/en/2.0.8/example/webserver/nginx.html

location ^~ /munin-cgi/munin-cgi-graph/ {
    fastcgi_split_path_info ^(/munin-cgi/munin-cgi-graph)(.*);
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_pass unix:/var/run/munin/fastcgi-graph.sock;
    include fastcgi_params;
}

似乎 nginx 正在使用 PCRE。 ^ 表示来自http://www.pcre.org/original/doc/html/pcrepattern.html 的“断言字符串开头(或行,在多行模式下)”,但我找不到 ~ 的含义。

谢谢

【问题讨论】:

标签: regex nginx pcre munin


【解决方案1】:

不要阅读 readthedocs.io 上的文档。如需全面解释,请阅读实际文档。

http://nginx.org/en/docs/http/ngx_http_core_module.html#location

我引用:

Syntax:   location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default:  —
Context:  server, location

所以这告诉我们^~location 支持的运算符之一。

换句话说:这根本不是任何正则表达式的一部分,它是一个修饰符。

文档继续:

为了找到与给定请求匹配的位置,nginx 首先检查使用前缀字符串(前缀位置)定义的位置。其中,匹配前缀最长的位置被选中并记忆。然后检查正则表达式 [...]

这意味着 nginx 首先尝试通过比较 URL 前缀来找到匹配项(速度快),如果失败,则继续尝试正则表达式(速度慢得多)。

几句话之后:

如果最长匹配前缀位置有“^~”修饰符,则不检查正则表达式。

所以这意味着如果给定 URL 存在候选匹配,那么您可以利用 ^~ 来阻止 nginx 尝试正则表达式来找到 更好的 匹配。这是性能优化。

所以,用简单的英语

location ^~ /munin-cgi/munin-cgi-graph/ {
}

表示“从/munin-cgi/munin-cgi-graph/ 开始的所有位置,不要费心寻找更好的匹配”

【讨论】:

    猜你喜欢
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多