• Post author:
  • Post category:nginx
  • Post comments:0评论

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 '网站正在维护中。';
    }
}

发表评论

验证码: − 1 = 1