nginx location匹配规则

原文链接:https://www.cpweb.top/559

1、用法

location用来控制访问网站的URL路径

Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }
        location @name { ... }
Default:	—
Context: server, location

2、location匹配符

匹配符匹配规则优先级
=精确匹配1
^~以某个字符串开头2
~区分大小写的正则匹配3
~*不区分大小写的正则匹配4
/通用匹配,任何请求都会匹配到5

3、优先级测试

[root@web01 ~]# vim /etc/nginx/conf.d/test.conf

server {
    listen 80;
    server_name localhost;

    location = / {
      default_type text/html;
      return 200 "location =";
    }
    
    location ^~ / {
      default_type text/html;
      return 200 "location ^~";
    }

    location ~ / {
      default_type text/html;
      return 200 "location ~";
    }

    location ~* / {
      default_type text/html;
      return 200 "location ~*";
    }

#   location / {
#     default_type text/html;
#     return 200 "location /";
#   }
}

4、匹配示例

[root@web01 ~]# vim /etc/nginx/conf.d/test1.conf

server {
    listen 81;
    server_name localhost;


#精准匹配,必须请求的uri是/status
    location = /status {
        default_type text/html;
        return 200 'location = /';
    }

#通用匹配,任何请求都会匹配到
    location / {
        default_type text/html;
        return 200 'location /';
    }

#通用匹配/documents/下任何请求都会匹配到
    location /documents/ {
        default_type text/html;
        return 200 'location /documents/';
    }

#匹配以images/开头的
    location ^~ /images/ {
        default_type text/html;
        return 200 'location ^~ /images/';
    }

#严格区分大小写,匹配以.php结尾的
    location ~ \.php$ {
        default_type text/html;
        return 200 '.php';
    }
    
#不区分大小写匹配,以.gif、.jpg、.jpeg后缀结尾的
    location ~* \.(gif|jpg|jpeg)$ {
        default_type text/html;
        return 200 'location ~* \.(gif|jpg|jpeg)';
    }
}

5、location @name { … }用法示例

如果出现异常返回404、403、401这样的状态码,都重定向到@error这个location上,而不是直接返回状态码。

server {
    listen 82;
    server_name localhost;
     
    error_page 404 403 401 @error;
    location @error {
        default_type text/html;
        return 200 '你可能是不小心走丢了。';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值