Nginx-location匹配规则

发布于:2024-07-03 ⋅ 阅读:(39) ⋅ 点赞:(0)


前言

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


一、location指令

nginx官方说明传送门

用法

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

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

二、location匹配规则

1. 匹配规则分类

类型 修饰 示例
前缀匹配 None location /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的执行逻辑是哪个而慌乱了。


网站公告

今日签到

点亮在社区的每一天
去签到