Nginx位置优先级

时间:2011-03-08 21:11:39

标签: nginx

位置指令会触发什么命令?

4 个答案:

答案 0 :(得分:271)

来自HttpCoreModule docs

  1. 带有“=”前缀且与查询完全匹配的指令。如果找到,则搜索停止。
  2. 使用传统字符串的所有剩余指令。如果此匹配使用“^〜”前缀,则搜索停止。
  3. 正则表达式,按照在配置文件中定义的顺序。
  4. 如果#3产生匹配,则使用该结果。否则,使用#2的匹配。
  5. 文档中的示例:

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

    如果它仍然令人困惑,here's a longer explanation

答案 1 :(得分:31)

按此顺序触发。

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

答案 2 :(得分:15)

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

答案 3 :(得分:1)

位置按以下顺序评估:

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

优先级前缀匹配(编号 2)与普通前缀匹配(编号 4)完全相同,但优先于任何正则表达式。

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

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

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