nginx 路径匹配
**********************
location
精准匹配(=):只匹配指定的请求路径
location = /aaa { #只匹配请求路径:/aaa,其余路径均不匹配
...
}
前缀匹配(^ ~):不使用正则表达式,匹配指定前缀开头的请求路径
location ^~ /aaa { #匹配以/aaa开头的请求路径,如:/aaa、/aaa/b、/aaa/bbb/ccc
...
}
正则匹配(~):匹配符合正则表达式的请求路径,区分大小写
location ~ \.html$ { #匹配以 .html结尾的请求路径
...
}
location ~ ^/aaa/.*\.html$ { #匹配以 /aaa开头、.html结尾的请求路径
...
}
正则匹配(~*):匹配符合正则表达式的请求路径,不区分大小写
location ~* \.html$ { #匹配以 .html结尾的请求路径
...
}
最大前缀匹配(无符号):使用前缀匹配度最大的location
#location 1
location /aaa {
...
}
#location 2
location /aaa/bbb {
...
}
/aaa/c ==> 匹配location 1
/aaa/bbb/c ==> 匹配location 2
匹配优先级:= ==> ^~ ==> ~/ ~* ==> 无符号匹配,优先级逐次降低
说明:当有多个正则匹配,使用最先匹配的location
**********************
注意事项
如果最大前缀相同,^~、无符号不能同时使用,会报错(前缀不同,可同时使用)
location ^~ /aaa {
root /usr/share/nginx/html;
}
location /aaa {
root /usr/share/nginx/html2;
}
报错信息:
[root@centos html]# docker logs nginx
2020/10/15 02:08:43 [emerg] 1#1: duplicate location "/aaa" in /etc/nginx/conf.d/default.conf:28
nginx: [emerg] duplicate location "/aaa" in /etc/nginx/conf.d/default.conf:28
**********************
优先级比较
^~ ==> ~
location ^~ /aaa {
root /usr/share/nginx/html2/2;
}
location ~ /aaa {
root /usr/share/nginx/html2/3;
}
curl localhost:8080/aaa
[root@centos html]# curl localhost:8080/aaa
location ^~ /aaa # ^~ 优先于 ~
~ ==> 无符号
location ~ /aaa {
root /usr/share/nginx/html2/3;
}
location /aaa {
root /usr/share/nginx/html2/4;
}
curl localhost:8080/aaa
[root@centos html]# curl localhost:8080/aaa
location ~ /aaa # ~ 优先于 无符号