Nginx Location匹配规则

前言:location是Nginx配置中的一个指令,用于访问的URL匹配,而在这个location中所配置的每个指令将会启动不同的 模块去完成相应的工作。

理论部分

一、location语法:

location [=|~|~*|^~] uri { … }

其中,方括号中的四种标识符是可选项,用来改变请求字符串和uri的匹配方式。uri是待匹配的请求字符串,可以是不包含正则的字符串,这种模式被称为“标准的uri";也可以包含正则,这种模式被称为"正则uri"。例如:

location ~ .*\.(php|php5)?$ {
  root /var/www/html;
  ……
}

二、四种可选标识符:

标识符描述
=精确匹配:用于标准uri前,要求请求字符串和uri严格匹配。如果匹配成功就停止匹配,立即执行该location里面的请求。
~正则匹配:用于正则uri前,表示uri里面包含正则,并且区分大小写
~*正则匹配:用于正则uri前,表示uri里面包含正则,不区分大小写
^~非正则匹配;用于标准uri前,nginx服务器匹配到前缀最多的uri后就结束,该模式匹配成功后,不会使用正则匹配。
普通匹配(最长字符匹配);与location顺序无关,是按照匹配的长短来取匹配结果。若完全匹配,就停止匹配

操作案例部分

一、环境准备

为了方便验证各匹配标识符,我们借助第三方模块  echo模块进行操作。安装步骤向右看?echo-nginx-module的安装、配置、使用

二、匹配标识符案例

1. “=”精准匹配

location = /news/ {
            echo "test1";
        }
[root@www quail]# curl 192.168.249.132/news/
test1

2.  "~"区分大小写正则匹配

location ~ \.(html) {
    echo 'test2';
}
location ~ \.(htmL) {
    echo 'test3';
}
[root@www quail]# curl 192.168.249.132/index.html
test2
[root@www quail]# curl 192.168.249.132/index.htmL
test3

3. “~*”不区分大小写的正则匹配

location ~* \.(html){
            echo 'test4';
}
[root@www quail]# curl 192.168.249.132/index.htmL
test4
[root@www quail]# curl 192.168.249.132/index.html
test4

4. “^~”不进行正则匹配的标准匹配,只匹配前缀

location ^~ /index/ {
            echo 'test5';
}
[root@www quail]# curl 192.168.249.132/index/
test5
[root@www quail]# curl 192.168.249.132/index/heihei
test5
[root@www quail]# curl 192.168.249.132/index/asdnmkalsjd
test5

5.普通匹配

location / {
            echo 'test6';
}
[root@www quail]# curl 192.168.249.132
test6

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值