Nginx嵌套位置优先级



这是我的nginx配置的一部分:

location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
location /wp-content/uploads/ {
location ~ .(aspx|php|jsp|cgi)$ { return 410; }
}

据我所知,位置块中的优先级顺序如下:

= (exact match)  -->  ^~ (preferential prefix)  -->  ~ (regex) or ~* (case-insensitive regex)  -->  (prefix - no special character)

我在/wp-content/uploads中放了一个PHP文件。我得到了一个410的响应代码(这正是我想要的(。但我不明白为什么第一个位置块没有捕获请求,因为regex块优先于前缀。

此外,当两个正则表达式位置匹配时,第一个声明的正则表达式位置将接受请求。然而,后者在这里处理请求。

为什么我得到/wp-content/uploads/info.php的410响应代码?!?

我找到了答案。nginx位置匹配有一个鲜为人知的秘密。

根据artfulrobot.uk的说法,以下是优先顺序:

1. Exact string matches location = /foo
2. The longest of any location ^~ ... matches
3. The first regex match that is nested within the single longest matching prefix match!
4. The first other regex match location ~ regex
5. The longest prefix match location /foo

每个人都知道#1、#2、#4和#5。

但第三名才是关键。这就是这里正在发生的事情

你会想阅读这篇文章,因为他非常详细地描述了nginx的这种看似没有记录和奇怪的行为。

最新更新