Nginx-location匹配规则


前言

Nginx在处理Http请求的时候,在NGX_HTTP_FIND_CONFIG_PHASE阶段,根据请求uri匹配location表达式,具体的匹配规则是怎么的呢,本节我们详细介绍下。


一、location指令

nginx官方说明传送门

用法

Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default:	—
Context:	server, location

可以看出,location指令是支持嵌套的。

二、location匹配规则

1. 匹配规则分类

类型修饰示例
前缀匹配Nonelocation /prefix 常规
前缀匹配=location = /exactmatch 精确匹配
前缀匹配^~location ^~ /longestmatchnotcheckreg 匹配上不再进行正则表达式
正则表达式~location ~ /regularsensitive 大小写敏感正则表达式
正则表达式~*location ~* /regularsensitive 忽略大小写正则表达式

2. 匹配顺序

在这里插入图片描述

1)先匹配前缀表达式,后匹配正则表达式。
2)前缀表达式如果匹配到严格匹配 location = /exactmatch, 则直接结束;
3)前缀表达式命中多条,则选择最长的, 如果最长的有正则中止修饰符 location ^~ /longestmatchnotcheckreg, 则结束;
4)顺序匹配正则表达式,一但匹配,则结束;
5)上面的正则表达式没有匹配到,则使用前面第三步最长的那条前缀规则,并结束;

三、location匹配示例

示例1

[root@private-172-20-37-61 test]# cat findlocation.conf 
server {
        server_name location.test.io;
        listen 8081;
        access_log off;
        default_type text/plain;

	location ~ /api/$ {
	  return 200 'first regular expressions match!\n';
	}

	location ~* /api/(\w+)$ {
	  return 200 'longest regular expressions match!\n';
	}			         

        location ^~ /api/ {
	  return 200 'stop regular expression match!\n';
	}

        location /api/test {
	  return 200 'logest prefix string match !\n';
	}

       location /api {
       	  return 200 'prefix string match!\n';
       }

       location = /api {
       	  return 200 'exact match!\n';
       }
}
输出结果:

```bash
[root@private-172-20-37-61 test]# curl http://location.test.io:8081/api
exact match!
[root@private-172-20-37-61 test]# curl http://location.test.io:8081/api/
stop regular expression match!
[root@private-172-20-37-61 test]# curl http://location.test.io:8081/api/test
longest regular expressions match!
[root@private-172-20-37-61 test]# curl http://location.test.io:8081/api/test/
logest prefix string match !
[root@private-172-20-37-61 test]# curl http://location.test.io:8081/api/Test/
stop regular expression match!
[root@private-172-20-37-61 test]# curl http://location.test.io:8081/api/Test
stop regular expression match!


总结

有了匹配规则和优先级的顺序,我们可以不用因为location的执行逻辑是哪个而慌乱了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值