简体   繁体   English

Nginx位置匹配中的变量捕获

[英]variable capture in Nginx location matching

Let's say I have a URL like this: www.example.com/a/b/sth , and I write a location block in Nginx config:假设我有一个这样的 URL: www.example.com/a/b/sth ,我在 Nginx 配置中写了一个位置块:

location ^~ /a/b/(?<myvar>[a-zA-Z]+) {
    # use variable $myvar here
    if ($myvar = "sth") { ... }
}

I hope to be able to use variable $myvar captured from the URL inside the block, however, Nginx keeps telling me this variable is not defined and won't start:我希望能够使用从块的 URL 捕获的变量$myvar ,但是,Nginx 一直告诉我这个变量没有定义并且不会启动:

nginx: [emerg] unknown "myvar" variable

Old thread but I had the same problem...旧线程,但我遇到了同样的问题...

I think the error isn't related to the PCRE version installed我认为该错误与安装的 PCRE 版本无关

NGINX doesn't parse your regex if your location tag doesn't start with ~ You need to use something like this如果您的位置标签不是以 ~ 您需要使用这样的东西开头,NGINX 不会解析您的正则表达式

location ~ ^/a/b/(?<myvar>[a-zA-Z]+) {
   # use variable $myvar here
   if ($myvar = "sth") { ... }
}

As Stefano Fratini correctly pointed out in his answer, your location declaration has an error: for regular expressions you should use ~ alone, not ^~ .正如 Stefano Fratini 在他的回答中正确指出的那样,您的location声明有一个错误:对于正则表达式,您应该单独使用~ ,而不是^~


Named captures are a feature of PCRE and they have different syntax available in different versions.命名捕获是 PCRE 的一项功能,它们在不同版本中具有不同的可用语法。 For the syntax you use ?<var> you must have PCRE 7.0 at least.对于你使用的语法?<var>你必须至少有 PCRE 7.0。

Please see the extensive information in official Nginx documentation请参阅官方 Nginx 文档中的大量信息

^~ is not regex match, it stands longest matching prefix. ^~ 不是正则表达式匹配,它代表最长匹配前缀。 you should use ~ or ~* (case insenstive) instead您应该使用 ~ 或 ~* (不区分大小写)代替

Untested, but the correct way to capture a block into a named variable using PCRE is (?P).未经测试,但使用 PCRE 将块捕获到命名变量中的正确方法是 (?P)。 So your example misses the P.所以你的例子错过了P。

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

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