一分钟搞懂nginx之location匹配和转发规则

tech2025-09-23  20

前言

location 匹配路由转发是nginx配置中最常见的配置,最近正在学习相关的知识,记录一下。

location配置规则

匹配规则=严格匹配,如果请求匹配这个location,则停止搜索并且处理这个请求~区分大小写匹配(可用正则表达式)~*不区分大小写匹配(可用正则表达式)!~区分大小写不匹配!~*区分大小写不匹配^~前缀匹配@“@” 定义一个命名的location,使用在内部定向时/通用匹配

location匹配顺序

"="精确匹配,如果匹配成功,则停止其他匹配普通字符串指令匹配,优先级是从长到短(匹配字符越多,则选择该匹配结果),匹配成功location如果使用 ^~,则停止匹配(正则匹配)正则表达式正则匹配,按照从上到下的原则,匹配成功,则停止匹配如果正则匹配成功,则使用该结果,否则使用普通字符串匹配

简单总结如下:

(location=)> (location完整路径)> (location^~路径) > (location正则顺序) > (location最长字符串匹配,不完全匹配) > (location通配)

即:

(精确匹配)> (最长字符串匹配,但完全匹配) >(非正则匹配)>(正则匹配)>(最长字符串匹配,不完全匹配)>(location通配)

location匹配实例

server { server_name location.test.com; listen 8010; location = / { return 200 "精确匹配/"; } location ~* /ma.*ch { return 200 "正则匹配/ma.*ch"; } location ~ /mat.*ch { return 200 "正则匹配/match.*"; } location = /test { return 200 "精确匹配/test"; } location ^~ /test/ { return 200 "前缀匹配/test"; } location ~ /test/he*o { return 200 "正则匹配/test/he*o"; } location / { return 200 "通配/"; } }

我们按照这样的 location 匹配实验结果如下:

# 精确匹配优先级最高 $ curl http://localhost:8010/ 精确匹配/ $ curl http://localhost:8010/test 精确匹配/test # 前缀匹配优先级高于正则匹配 $ curl http://localhost:8010/test/heeo 前缀匹配/test # 正则匹配,按照顺序依次匹配,如果同时匹配两个正则,则前面的优先匹配 $ curl http://localhost:8010/matxxch 正则匹配/ma.*ch # 什么都匹配不到时,最后匹配通配/ $ curl http://localhost:8010/xxxxx 通配/
最新回复(0)