Nginx位置优先级


186

位置指令按什么顺序触发?

Answers:


352

HTTP核心模块docs

  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 ] 
}

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



4
请注意,//documents/规则都与request匹配/documents/index.html,但是后一个规则是优先的,因为它是最长的规则。
arrakis_sun

69

它按此顺序触发。

  1. = (究竟)

    location = /path

  2. ^~ (前场比赛)

    location ^~ /path

  3. ~ (正则表达式区分大小写)

    location ~ /path/

  4. ~* (正则表达式不区分大小写)

    location ~* .(jpg|png|bmp)

  5. /

    location /path


3
^〜(前场比赛)非常重要
iwind

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.