当前位置: 代码网 > it编程>数据库>Redis > Nginx location匹配模式与规则详解

Nginx location匹配模式与规则详解

2025年04月23日 Redis 我要评论
一、环境nginx 1.19二、匹配模式在 nginx 的location指令里,常用的匹配模式有:精准模式(=)前缀模式,不继续匹配正则(^~),前缀模式,继续匹配正则,正则模式,大小写敏感(~)正

一、环境

nginx 1.19

二、匹配模式

在 nginx 的location指令里,常用的匹配模式有:

  • 精准模式(=)
  • 前缀模式,不继续匹配正则(^~),
  • 前缀模式,继续匹配正则,
  • 正则模式,大小写敏感(~)
  • 正则模式,大小写不敏感(~*)

1. 精准模式

location = /path {
    default_type text/html;
    return 200 'hello';
}

2. 前缀模式(不继续匹配正则)

location ^~ /path {
    default_type text/html;
    return 200 'hello';
}

3. 前缀模式(继续匹配正则)

location /path {
    default_type text/html;
    return 200 'hello';
}

4. 正则模式(大小写敏感)

location ~ /path {
    default_type text/html;
    return 200 'hello';
}

5. 正则模式(大小写不敏感)

location ~* /path {
    default_type text/html;
    return 200 'hello';
}

nginx会按照 精准模式 -> 前缀模式 -> 正则模式 的顺序来匹配。

精准模式优先级最高,匹配到后就不再继续匹配其它模式。而前缀模式匹配到后,还要视乎指令的配置情况,来决定要不要继续匹配正则模式。

三、需要注意的地方

1. 命中多个正则模式时的优先级

看例子:

# 正则模式(大小写敏感)
location ~ /a {
    default_type text/html;
    return 200 '111';
}

# 正则模式(大小写敏感)
location ~ /a/b {
    default_type text/html;
    return 200 '222';
}

如果访问http://localhost/a/b,会命中哪个location?答案是第一个。

因为两个location都是正则模式(无论是否大小写敏感),从上之下,哪个先匹配到就哪个负责处理

2. 命中多个前缀模式时的优先级

# 前缀模式(继续匹配正则)
location /a {
    default_type text/html;
    return 200 '111';
}

# 前缀模式(继续匹配正则)
location /a/b {
    default_type text/html;
    return 200 '222';
}
  • 访问http://localhost/a,命中第一个;
  • 访问http://localhost/a/b,命中第二个;
  • 访问http://localhost/a/b/c,命中第二个;

简单来说,哪个location匹配到的字符串最长,就由哪个来处理,比如http://localhost/a/b/c能匹配到的最长字符串是/a/b,所以由第二个location来处理。

前缀模式(不继续匹配正则)也是同样的匹配规则。

3. 命中多个不同模式时的优先级

# 前缀模式(不继续匹配正则)
location ^~ /a {
    default_type text/html;
    return 200 '111';
}

# 前缀模式(继续匹配正则)
location /a/b {
    default_type text/html;
    return 200 '333';
}

# 正则模式(大小写敏感)
location ~ /a/b {
    default_type text/html;
    return 200 '222';
}

访问http://localhost/a/b,会命中第三个location

前面两个location都是前缀模式,由匹配字符串最长的处理(即第二个)。第二个location没有阻止继续匹配正则,于是又继续匹配第三个location(正则模式),所以最后是由第三个location处理。

4. 两种前缀模式不能同时存在

看例子:

# 前缀模式(不继续匹配正则)
location ^~ /a {
    default_type text/html;
    return 200 '333';
}

# 前缀模式(继续匹配正则)
location /a {
    default_type text/html;
    return 200 '444';
}

上面这段配置 nginx 会报错,因为在路径相同的情况下,这两种模式不能共存。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com