Fork me on GitHub

nginx location优先级

网上查了下location的优先级规则,但是很多资料都说的模棱两可,自己动手实地配置了下,下面总结如下。

1. 配置语法

1> 精确匹配

    location = /test {
        ...
    }

2> 前缀匹配

  • 普通前缀匹配
    location  /test {
        ...
    }
  • 优先前缀匹配
    location  ^~ /test {
        ...
    }

3> 正则匹配

  • 区分大小写
    location  ~ /test$ {
        ...
    }
  • 不区分大小写
    location  ~* /test$ {
        ...
    }

2. 配置实例

1> 多个前缀匹配,访问/test/a,则先记住最长的前缀匹配,并继续匹配

    location / {
        root   html;
        index  index.html index.htm;
    }
    
    location /test {
        return 601;
    }

    location /test/a {
        return 602;
    }

命中的响应状态码

602

2> 前缀匹配和正则匹配,访问/test/a,则命中正则匹配

    location / {
        root   html;
        index  index.html index.htm;
    }
    
    location /test/a {
        return 601;
    }

    location ~* /test/a$ {
        return 602;
    }

命中的响应状态码

602

3> 优先前缀匹配和正则匹配,访问/test/a,则命中优先前缀匹配,终止匹配

    location / {
        root   html;
        index  index.html index.htm;
    }
    location ^~ /test/a {
        return 601;
    }

    location ~* /test/a$ {
        return 602;
    }

命中的响应状态码

601

4> 多个正则匹配命中,访问/test/a,则使用第一个命中的正则匹配,终止匹配

    location / {
        root   html;
        index  index.html index.htm;
    }
    
    location ~* /a$ {
        return 601;
    }          
               
    location ~* /test/a$ {
        return 602;
    }

命中的响应状态码

601

5> 精确匹配和正则匹配,访问/test,精确匹配优先

    location / {
        root   html;
        index  index.html index.htm;
    }

    location ~* /test {
        return 602;
    }

    location = /test {
        return 601;
    }

命中的响应状态码

601

3. 总结:

  • 搜索优先级:
精确匹配 > 字符串匹配( 长 > 短 [ 注: ^~ 匹配则停止匹配 ]) > 正则匹配( 上 > 下 )
  • 使用优先级:
精确匹配 > (^~) > 正则匹配( 上 > 下 )>字符串(长 > 短)

解释:

  • 先搜索有没有精确匹配,如果匹配就命中,终止匹配。
  • 索前缀匹配,命中则先记住(可能命中多个),继续往下搜索,如果有优先前缀匹配符号“^~”,则命中优先前缀匹配,不再去检查正则表达式;反之则继续进行正则匹配,如果命中则使用正则表达式,如果没命中则使用最长的前缀匹配。
  • 前缀匹配,长的优先;多个正则匹配,在上面的优先。
posted @ 2018-12-04 20:44  archer-wong  阅读(271)  评论(0编辑  收藏  举报