美文网首页
nginx之location优先级

nginx之location优先级

作者: 唯爱熊 | 来源:发表于2020-02-06 14:04 被阅读0次

location优先级对比

= 高于 ^~ 高于 ~* 等于 ~ 高于 /
对比/和~
示例1:

server{
    listen 80;
    server_name www.weiaixiong.com;
    root /tmp/123.com;

    location /abc/
    {
        echo "/";
    }
    location ~ 'abc'
    {
        echo "~";
    }
}

测试命令:curl -x127.0.0.1:80 'www.weiaixiong.com/abc/1.png'
结果是:~
对比~*
示例2:

server
{
    listen 80;
    server_name www.weiaixiong.com;
    root /tmp/123.com;

    location ~ 'abc'
    {
        echo '~';
    }
    location ~* 'abc'
    {
        echo '~*';
    }
}

测试命令:curl -x127.0.0.1:80 'www.weiaixiong.com/abc/123.html'
结果是:~

示例3:

server
{
    listen 80;
    server_name www.weiaixiong.com;
    root /tmp/123.com;

    location ~* 'abc'
    {
        echo '~*';
    }
    location ~ 'abc'
    {
        echo '~';
    }
}

测试命令:curl -x127.0.0.1:80 'www.weiaixiong.com/abc/123.html'
结果是:~*

结论: ~和~*优先级其实是一样的,如果两个同时出现,配置文件中哪个location靠前,哪个生效。
对比^~
示例4:

server
{
    listen 80;
    server_name www.weiaixiong.com;
    root /tmp/123.com;

    location ~ '/abc'
    {
        echo '~';
    }
    location ^~ '/abc'
    {
        echo '^~';
    }
}

测试命令:curl -x127.0.0.1:80 'www.weiaixiong.com/abc/123.html
结果是:^~
对比=和^~
示例5:

server
{
    listen 80;
    server_name www.weiaixiong.com;
    root /tmp/123.com;

    location ^~ '/abc.html'
    {
        echo '^~';
    }
    location = '/abc.html'
    {
        echo '=';
    }
}

测试命令:curl -x127.0.0.1:80 'www.weiaixiaong.com/abc.html
结果是:=

nginx的location配置

nginx location语法规则:location [=|||^~] /uri/ { … }
nginx的location匹配的变量是$uri
符号 说明
= 表示精确匹配
^~ 表示uri以指定字符或字符串开头
~ 表示区分大小写的正则匹配
~
表示不区分大小写的正则匹配
/ 通用匹配,任何请求都会匹配到
规则优先级
= 高于 ^~ 高于 ~* 等于 ~ 高于 /
规则示例
location = "/12.jpg" { ... }
如:
www.weiaixiong.com/12.jpg 匹配
www.weiaixiong.com/abc/12.jpg 不匹配

location ^~ "/abc/" { ... }
如:
www.weiaixiong.com/abc/123.html 匹配
www.weiaixiong.com/a/abc/123.jpg 不匹配

location ~ "png" { ... }
如:
www.weiaixiong.com/aaa/bbb/ccc/123.png 匹配
www.weiaixiong.com/aaa/png/123.html 匹配

location ~* "png" { ... }
如:
www.weiaixiong.com/aaa/bbb/ccc/123.PNG 匹配
www.weiaixiong.com/aaa/png/123.html 匹配

location /admin/ { ... }
如:
www.weiaixiong.com/admin/aaa/1.php 匹配
www.weiaixiong.com/123/admin/1.php 不匹配
小常识
有些资料上介绍location支持不匹配 !~,
如: location !~ 'png'{ ... }
这是错误的,location不支持 !~
注意:location优先级小于if
如果有这样的需求,可以通过if来实现,
如: if ($uri !~ 'png') { ... }

相关文章

网友评论

      本文标题:nginx之location优先级

      本文链接:https://www.haomeiwen.com/subject/xczyxhtx.html