nginx中location的匹配规则和优先级
|
admin
2025年6月28日 22:30
本文热度 24
|
匹配规则
- 精确匹配,以
=
开头。如:location = /index.html {
return 200 "精确匹配/index.html";
}
- 普通匹配,没有任何修饰符。如:
location /images/ {
return 200 "普通匹配,匹配以/images/开头的URI";
}
- 正则匹配,以
~
开头,~
表示区分大小写,~*
表示不区分大小写。如:location ~ \.js$ {
return 200 "匹配.js结尾的URI";
}
location ~* \.jpg$ {
return 200 "匹配.JPG或.jpg结尾的URI";
}
- 前缀匹配,以
^~
开头,如location ^~ /images/ {
return 200 "前缀匹配,匹配以/images/开头的URI";
}
匹配优先级
不同匹配优先级从高到低为:
~
~*
正则匹配,正则匹配中遇到第一个满足的匹配就返回。
优先级测试
一、配置规则
location /home {
return 200 "home目录";
}
location / {
return 200 "根目录";
}
location = /index.html {
return 200 "精确匹配/index.html";
}
location ^~ /index.html {
return 200 "前缀匹配/index.html";
}
location ^~ /content/ {
return 200 "前缀匹配,匹配以/content/开头的URI";
}
location ~ \.html$ {
return 200 "正则匹配,匹配.html结尾的URI";
}
location ~ logo\.jpg$ {
return 200 "正则匹配,匹配logo.jpg结尾的URI";
}
location ~ \.jpg$ {
return 200 "正则匹配,匹配.jpg结尾的URI";
}
location /images/logo/ {
return 200 "普通匹配,匹配以/images/logo/开头的URI";
}
location /images/ {
return 200 "普通匹配,匹配以/images/开头的URI";
}
二、测试
- GET http://localhost:85/index.html
- 同时满足
/index.html
和^~ /index.html
,返回精确匹配/index.html
- GET http://localhost:85/content/home.html
- 同时满足
^~ /content/
和~ \.html$
,返回前缀匹配,匹配以/content/开头的URI
- GET http://localhost:85/images/logo/1.jpg
- 同时满足
~ \.jpg$
和/images/logo/
,返回正则匹配,匹配.jpg结尾的URI
- GET http://localhost:85/logo.jpg
- 同时满足
~ logo\.jpg$
和~ \.jpg$
,返回正则匹配,匹配logo.jpg结尾的URI
- GET http://localhost:85/logo1.jpg
- GET http://localhost:85/images/logo/1.png
- 同时满足
/images/logo/
和/images/
,返回普通匹配,匹配以/images/logo/开头的URI
- GET http://localhost:85/home/1.action
- 精确匹配、前缀匹配、正则匹配都不满足,仅匹配了普通匹配中最短匹配
- GET http://localhost:85/static/1.action
阅读原文:原文链接
该文章在 2025/7/1 23:39:46 编辑过