Nginx位置优先级

use*_*505 163 nginx

位置指令触发的命令是什么?

Mar*_*ond 308

来自HttpCoreModule文档:

  1. 带有"="前缀且与查询完全匹配的指令.如果找到,搜索停止.
  2. 所有剩余的指令与传统的字符串.如果此匹配使用"^〜"前缀,则搜索停止.
  3. 正则表达式,按照在配置文件中定义的顺序.
  4. 如果#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 ] 
}
Run Code Online (Sandbox Code Playgroud)

如果它仍然令人困惑,这里有一个更长的解释.

  • 它可以帮助你:)https://github.com/detailyang/nginx-location-match-visible (7认同)
  • 请注意,`/`和`/ documents /`规则都匹配请求`/ documents/index.html`,但后者规则优先,因为它是最长的规则. (4认同)

Don*_*nga 48

它按此顺序触发.

  1. =(确切地说):location =/path
  2. ^〜(前进匹配):位置^〜/路径
  3. 〜(正则表达式区分大小写):位置〜/ path /
  4. 〜*(正则表达式不区分大小写):location~*.(jpg | png | bmp)
  5. /:位置/路径

  • ^~(正向匹配)非常重要 (5认同)
  • 省略尾部斜杠将不仅仅是精确匹配。#1 应为 `location = /path/`,其他应包含开始和结束修饰符(`^` 和 `$`) (3认同)

Ice*_*erg 24

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

  • 这非常有用! (2认同)

小智 16

位置按以下顺序评估:

  1. location = /path/file.ext {}完全符合
  2. location ^~ /path/ {}优先前缀匹配 -> 最长优先
  3. location ~ /Paths?/ {}(区分大小写的正则表达式) location ~* /paths?/ {}(不区分大小写的正则表达式)-> 第一个匹配
  4. location /path/ {}前缀匹配 -> 最长优先

优先级前缀匹配(数字 2)与公共前缀匹配(数字 4)完全相同,但优先于任何正则表达式。

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

区分大小写和不区分大小写具有相同的优先级。评估在第一个匹配规则处停止。

文档称所有前缀规则都会在任何正则表达式之前进行评估,但如果一个正则表达式匹配,则不会使用标准前缀规则。这有点令人困惑,并且不会改变上面报告的优先级顺序的任何内容。