location语法匹配详解

匹配符解释

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

location优先级示例

cat location.conf
server {
    listen 80;
    server_name www.location.com;

    location = / {
        default_type text/html;
        return 200 'location = /';
    }

    location / {
        default_type text/html;
        return 200 'location /';
    }

    location /documents/ {
        default_type text/html;
        return 200 'location /documents/';
    }

    location ^~ /images/ {
        default_type text/html;
        return 200 'location ^~ /images/';
    }

    location ~* .(gif|jpg|jpeg)$ {
        default_type text/html;
        return 200 'location ~* .(gif|jpg|jpeg)';
    }
}

# 1.等号精确匹配优先,no.1
curl www.location.com/
location = /

# 2.^~ ,以某个字符串开头no.2
curl www.location.com/images/1.gif
location ^~ /images/

# 3.~* 不区分大小写的正则匹配
curl www.location.com/documents/1.jpg
location ~* .(gif|jpg|jpeg)

# 4.目录匹配
curl www.location.com/documents/1.html
location /documents/

# 5. / 通用匹配,任何请求都会匹配到no.5
curl www.location.com/index.html
location /
posted @ 2025-08-14 21:20  阿峰博客站  阅读(16)  评论(0)    收藏  举报