Nginx 中的 PCRE ^~ 符号

PCRE ^~ symbol in nginx

我有这个 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 中的 "assert start of string (or line, in multiline mode)" 但我找不到 ~ 的意思。

谢谢

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

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

我引用:

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

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

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

文档继续:

To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked [...]

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

几句话后:

If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.

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

所以,用简单的英语

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

表示"all locations starting /munin-cgi/munin-cgi-graph/, and don't bother looking for better matches".