0%

Nginx 中 location 的优先级

遇到问题

在部署 nginx 服务器时,遇到了一个问题,即 nginx 下的 location 有多个条件。

1
2
3
4
5
6
7
8
9
location / {
root /var/www/webapp;
index index.html index.htm index.php;
}

location /go {
root /var/www/webapp;
index index.html index.htm index.php;
}

这时,如果有越来越多的规则难免令人疑惑,究竟是哪一个的优先级更高?

寻求答案

翻阅 nginx 手册,有如下一段话

  1. Test the URI against all prefix strings.
  2. The = (equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
  3. If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked.
  4. Store the longest matching prefix string.
  5. Test the URI against regular expressions.
  6. Break on the first matching regular expression and use the corresponding location.
  7. If no regular expression matches, use the location corresponding to the stored prefix string.

翻译如下

  1. 测试所有的前缀字符串。
  2. “=” 定义了 URI 和前缀的完全匹配。如果匹配,停止搜索。
  3. 如果 “^~” 表达式和 URI 完全匹配,将会直接返回对应的 location ,其他的常规正则表达式不会再被检查。
  4. 存储最长匹配的常规前缀字符串。
  5. 测试正则表达式。
  6. 在第一次 URI 匹配到正则表达式时,将会终止匹配并使用对应的 location。
  7. 如果没有匹配的正则,就使用第4步中存储的最长的前缀对应的 location。

结论

第一优先级:等号类型(=)的优先级最高。一旦匹配成功,则不再查找其他匹配项。
第二优先级:^~类型表达式。一旦匹配成功,则不再查找其他匹配项。
第三优先级:正则表达式类型~, ~*的优先级次之。如果有多个location的正则能匹配的话,则使用正则表达式最长的那个。
第四优先级:常规字符串匹配类型。按前缀匹配。

参考:

CONFIGURING NGINX PLUS AS A WEB SERVER