2024-04-13 06:00:05

Nginx位置优先级

位置指令的发射顺序是什么?


来自HTTP核心模块文档:

带有“=”前缀的指令精确匹配查询。如果找到,搜索就会停止。 所有剩余的常规字符串指令。如果匹配使用了“^~”前缀,则停止搜索。 正则表达式,按照它们在配置文件中定义的顺序。 如果#3产生了匹配,则使用该结果。否则,使用来自#2的匹配。

文档中的示例:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

如果你仍然感到困惑,这里有一个更长的解释。

它按这个顺序发射。

=(完全) Location = /path ^~(前向匹配) 位置^~ /路径 ~(正则表达式区分大小写) 位置~ /路径/ ~*(正则表达式不区分大小写) 位置~* .(jpg|png|bmp) / 位置/路径

现在有一个方便的在线工具可以测试位置优先级: 位置优先级在线测试

位置的计算顺序如下:

Location = /path/file。ext{}完全匹配 location ^~ /path/{}优先级前缀匹配->最长优先 location ~ /路径?/{}(区分大小写的regexp)和location ~* /paths?/{}(不区分大小写的regexp) ->第一个匹配 location /path/{}前缀匹配->长度优先

优先级前缀匹配(编号2)与公共前缀匹配(编号4)完全相同,但优先级高于任何regexp。

对于这两种前缀匹配类型,最长的匹配获胜。

区分大小写和不区分大小写具有相同的优先级。求值止于第一个匹配规则。

文档说,所有前缀规则都在任何regexp之前计算,但如果一个regexp匹配,则不使用标准前缀规则。这有点令人困惑,并且没有改变上面报告的优先级顺序。