遇到问题
在部署 nginx 服务器时,遇到了一个问题,即 nginx 下的 location 有多个条件。
1 | location / { |
这时,如果有越来越多的规则难免令人疑惑,究竟是哪一个的优先级更高?
寻求答案
翻阅 nginx 手册,有如下一段话
- Test the URI against all prefix strings.
- The = (equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
- If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked.
- Store the longest matching prefix string.
- Test the URI against regular expressions.
- Break on the first matching regular expression and use the corresponding location.
- If no regular expression matches, use the location corresponding to the stored prefix string.
翻译如下
- 测试所有的前缀字符串。
- “=” 定义了 URI 和前缀的完全匹配。如果匹配,停止搜索。
- 如果 “^~” 表达式和 URI 完全匹配,将会直接返回对应的 location ,其他的常规正则表达式不会再被检查。
- 存储最长匹配的常规前缀字符串。
- 测试正则表达式。
- 在第一次 URI 匹配到正则表达式时,将会终止匹配并使用对应的 location。
- 如果没有匹配的正则,就使用第4步中存储的最长的前缀对应的 location。
结论
第一优先级:等号类型(=)的优先级最高。一旦匹配成功,则不再查找其他匹配项。
第二优先级:^~
类型表达式。一旦匹配成功,则不再查找其他匹配项。
第三优先级:正则表达式类型~
, ~*
的优先级次之。如果有多个location的正则能匹配的话,则使用正则表达式最长的那个。
第四优先级:常规字符串匹配类型。按前缀匹配。
参考: