【问题标题】:Nginx location priorityNginx 位置优先级
【发布时间】:2011-07-11 10:28:51
【问题描述】:

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

【问题讨论】:

    标签: nginx


    【解决方案1】:

    来自HTTP core module 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 ] 
    }
    

    如果仍然感到困惑,here's a longer explanation

    【讨论】:

    【解决方案2】:

    按此顺序触发。

    1. = (完全正确)

      location = /path

    2. ^~ (前锋)

      location ^~ /path

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

      location ~ /path/

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

      location ~* .(jpg|png|bmp)

    5. /

      location /path

    【讨论】:

    • ^~(前锋比赛)非常重要
    • 去掉尾部的斜线将不仅仅匹配精确。 #1 应该是location = /path/,其他应该包括开始和结束修饰符(^$
    • location = /path 匹配 domain.com/path,location = /path/ 匹配 domain.com/path/。其他人不需要开始和结束修饰符。
    【解决方案3】:

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

    【讨论】:

    • 这个很有用!
    【解决方案4】:

    按以下顺序评估位置:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2016-07-08
      • 2020-08-02
      • 2018-05-09
      • 1970-01-01
      相关资源
      最近更新 更多