zoukankan      html  css  js  c++  java
  • 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. 总结:

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

    解释:

    • 先搜索有没有精确匹配,如果匹配就命中,终止匹配。
    • 索前缀匹配,命中则先记住(可能命中多个),继续往下搜索,如果有优先前缀匹配符号“^~”,则命中优先前缀匹配,不再去检查正则表达式;反之则继续进行正则匹配,如果命中则使用正则表达式,如果没命中则使用最长的前缀匹配。
    • 前缀匹配,长的优先;多个正则匹配,在上面的优先。
  • 相关阅读:
    HTML浏览器标题栏如何设置
    阿里团队常用的布局——双飞翼布局
    浏览器兼容性问题——IE不支持却很实用的CSS属性Outline和Child
    css选择器:基本选择器
    编程十年
    解决WX-IOS打开公众号网页出现的底部导航条
    Angular6路由复用与延迟加载的冲突解决——看看有备无患
    Ionic2 + Angular4 + JSSDK开发中的若干问题汇总
    [Linq Expression]练习自己写绑定
    [Linq To Sql]解决join时的Collation冲突
  • 原文地址:https://www.cnblogs.com/redirect/p/10066744.html
Copyright © 2011-2022 走看看