nginx location优先级

目录

1 nginx location语法规则

2 规则优先级

3 规则示例

 4 优先级演示示例


1 nginx location语法规则

语法规则:location [=|~|~*|^~] /uri/ { … } 

nginx的location匹配的变量是$uri
符号说明
=表示精确匹配
^~表示uri以指定字符或字符串开头
~*表示不区分大小写的正则匹配
~表示区分大小写的正则匹配
/通用匹配,任何请求都会匹配到

2 规则优先级

= 高于 ^~ 高于 ~* 等于 ~ 高于 /

3 规则示例

location = "/12.jpg" { ... }
如:
bfd-wyl.cn/12.jpg 匹配
bfd-wyl.cn/abc/12.jpg 不匹配

location ^~ "/abc/" { ... }
如:
bfd-wyl.cn/abc/123.html 匹配
bfd-wyl.cn/a/abc/123.jpg 不匹配

location ~ "png" { ... }
如:
bfd-wyl.cn/aaa/bbb/ccc/123.png 匹配
bfd-wyl.cn/aaa/png/123.html 匹配

location ~* "png" { ... }
如:
bfd-wyl.cn/aaa/bbb/ccc/123.PNG 匹配
bfd-wyl.cn/aaa/png/123.html 匹配


location /admin/ { ... }
如:
bfd-wyl.cn/admin/aaa/1.php 匹配
bfd-wyl.cn/123/admin/1.php 不匹配

 4 优先级演示示例

1.nginx的配置内容如下:

[root@wyl01 conf.d]# cat default.conf
server {
    listen       80;
    server_name  localhost;

    location / {
         return 601;
    }
    

   location ~ /wyl/index.html {
      return 602;
    }

  
   location ~* /wyl/index.html {
      return 603;
    }
   
    location ^~ /wyl {
      return 604;
    }

  
    location = /wyl/index.html {
     return 605;
    }
}

示例1:nginx的配置文件保持上述内容不变

#示例一 我们看到"="号优先级最高,匹配到了最下面的location了。
[root@wyl01 conf.d]# curl  -w "%{http_code}" 106.12.74.123/wyl/index.html;echo ''
605

示例2:nginx的配置内容我们去掉最后一个=匹配的location,再次验证

[root@wyl01 conf.d]# curl  -w "%{http_code}" 106.12.74.123/wyl/index.html;echo ''
604

示例3:nginx的配置内容我们去掉=和^~匹配的location,再次验证

[root@wyl01 conf.d]# curl  -w "%{http_code}" 106.12.74.123/wyl/index.html;echo ''
603

示例3:nginx的配置内容我们保留前两个localtion,再次验证

[root@wyl01 conf.d]# curl  -w "%{http_code}" 106.12.74.123/wyl/index.html;echo ''
602

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值