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. 总结:

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

    解释:

    • 先搜索有没有精确匹配,如果匹配就命中,终止匹配。
    • 索前缀匹配,命中则先记住(可能命中多个),继续往下搜索,如果有优先前缀匹配符号“^~”,则命中优先前缀匹配,不再去检查正则表达式;反之则继续进行正则匹配,如果命中则使用正则表达式,如果没命中则使用最长的前缀匹配。
    • 前缀匹配,长的优先;多个正则匹配,在上面的优先。
  • 相关阅读:
    IE8下网页中的视频会遮挡住顶层DIV的解决办法
    Synchronized 偏向锁、轻量级锁、自旋锁、锁消除
    Lock的使用
    Synchronized与ReentrantLock区别总结(简单粗暴,一目了然)
    Java线程池 面试题(精简)
    Java 线程池的认识和使用
    bat等大公司常考java多线程面试题
    Java面试题必备知识之ThreadLocal
    阿里面试题
    Spring中Bean的生命周期
  • 原文地址:https://www.cnblogs.com/redirect/p/10066744.html
Copyright © 2011-2022 走看看