【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 会报错,因为在路径相同的情况下,这两种模式不能共存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值