Nginx之location匹配规则

柳三千

文章最后更新时间:2022年10月06日已超过713天没有更新。

前言:

   location是根据url传回来的值进行匹配,然后进行相应的定位。在虚拟主机的配置中,是必不可少的。location可以将网站的不同部分,定位到不同的处理方式上。


一、Nginx常用的正则表达式

1、nginx正则表达式的字符含义

字符含义
.匹配任意单个字符
^行首锚定, 用于模式的最左侧
$行尾锚定,用于模式的最右侧
*匹配前面字符任意次(包括0次)
?0或1次
+1次或多次(1次或以上)
\转义符
\d只匹配数字
{n}重复n次
{n,}至少n次(n次货以上)
{n,m}n到m次
[ ]定义匹配字符的范围,只匹配一次
[c]单个字
[a-z]匹配任意小写字母
[a-zA-Z0-9]匹配任意字母和数
()表达式的开始和结束位置
a | b或运算符a|b


2、location常用的匹配规则

规则表达式
规则含义
=
精确匹配
^~
表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其他 location
~
正则匹配,区分大小写
~*
正则匹配,不区分大小写


二、location匹配规则

url地址:http://xxx.com/test 会取出“/test”的值与 location /who_test.html location 的   '/who_test.html' 值 匹配

1、生成三个文件,内容分别如下:

[root@WEB nginx]# cat test/test.html 
<h1>test.html</h1>


[root@WEB nginx]# cat /home/test/test.html
<html>
<meta charset='UTF-8 '/>
我是正则匹配出来的test
</html>


[root@WEB nginx]# cat /home/tp/123.html 
<h1>/home/tp/123</h1>


2、配置文件如下:

location /test.html{
    root test;    
}

location /who_test.html {
            root   test;
}
        
location /123 {
            root   /home/tp;
}
        
location ~ test {
        root /home/test;
}


3、验证谁生效

图片.png


结论:正则匹配的值覆盖了一般匹配的值,优先级比一般匹配高


4、把一般匹配修改成精准匹配

location = /test.html{#精准匹配
    root test;    
}

location /who_test.html {
            root   test;
}

location /123 {
            root   /home/tp;
}
 
location ~ test {
    root /home/test;
}

           图片.png

结论:精准匹配优先级大于正则匹配,精准匹配生效


5、多个一般匹配冲突

location /test.ht{
        root test;
}
location /who_test.html {
            root   test;
}
location /test.htm {
            root   /home/tp;
}
location /test.h {
        root /home/test;
}

图片.png

找不到文件,看看报错路径

[root@WEB nginx]# tail -1 logs/error.log 
2022/09/30 16:17:35 [error] 1684083#0: *58498 open() "/home/tp/test.html" failed (2: No such file or directory), client: 157.122.113.58, server: www.liudx.cn, request: "GET /test.html HTTP/1.1", host: "liudx.cn"

图片.png

这个目录下确实没有test.html文件,说明是这个location生效

location /test.htm {
            root   /home/tp;
}

结论:一般匹配,匹配的值最长的生效


总结:location的命中过程

    1、先判断精准匹配,如果命中,立即返回结果并结束解析过程。

    2、判断普通命中,如果有多个命中,记录最长的命中结果(注意:记录最长的值但不结束,继续匹配)

    3、继续判断正则表达式的解析结果,按配置里的正则表达式顺序为准,由上到下开始匹配,一旦匹配成功,立即返回结果,并结束解析过程

延伸分析:

    a:普通命中,顺序无所谓,因为按命中的长短来确定的

    b:正则命中,先命中为准

文章版权声明:除非注明,否则均为柳三千运维录原创文章,转载或复制请以超链接形式并注明出处。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码