Powered by Typecho)))
Optimized by EAimTY
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
1. location [ = | ~ | ~* | ^~ ] uri { ... }
2. location @name { ... }
location 配置可以有两种配置方法
1.前缀 + uri(字符串/正则表达式)
2.@ + name
前缀含义
= :精确匹配(必须全部相等)
~ :大小写敏感
~* :忽略大小写
^~ :只需匹配uri部分
@ :内部服务跳转
Location 基础知识
1.location 是在 server 块中配置。
2.可以根据不同的 URI 使用不同的配置(location 中配置),来处理不同的请求。
3.location 是有顺序的,会被第一个匹配的location 处理。
1.=,精确匹配
location = / {
#规则
}
# 则匹配到 `http://www.example.com/` 。
2.~,大小写敏感
location ~ /Example/ {
#规则
}
#请求示例
#http://www.example.com/Example/ [成功]
#http://www.example.com/example/ [失败]
3.~*,大小写忽略
location ~* /Example/ {
#规则
}
# 则会忽略 uri 部分的大小写
#http://www.example.com/Example/ [成功]
#http://www.example.com/example/ [成功]
4.^~,只匹配以 uri 开头
location ^~ /img/ {
#规则
}
#以 /img/ 开头的请求,都会匹配上
#http://www.example.com/img/a.jpg [成功]
#http://www.example.com/img/b.mp4 [成功]
5.@,nginx内部跳转
location /img/ {
error_page 404 @img_err;
}
location @img_err {
# 规则
}
#以 /img/ 开头的请求,如果链接的状态为 404。则会匹配到 @img_err 这条规则上。
1:前缀匹配和精确匹配优先级最高,取最长匹配。
2:正则匹配顺序为nginx配置文件里location书写顺序,无相 应匹配规则时,以最早一次前缀匹配为准。
3:@匹配通常用于重定向,无单独匹配规则,无法被嵌套,本身也不能包含嵌套。
4:location可嵌套。
5:nginx先检查前缀字符串,然后检查正则表达式,如果前缀匹配匹配到了,并且前缀匹配有“^~” 修饰符,就不配正则了;如果没有“^~” ,即使前缀匹配到了,也要去匹配正则表则,如果正则表达式匹配到了,就是用正则表达式的,没有就是用前缀字符串匹配到的路径;
6:
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
上述匹配顺序如下:
1: “/” 匹配规则 A,
2:“/index.html” 匹配规则B,
3:“/documents/document.html” 匹配规则C,
4:“/images/1.gif” 匹配规则D,
5:“/documents/1.jpg”匹配规则E。
顺序A>E>C>D>C>B
规则:无“^~”, 最终使用正则匹配到的路径,正则匹配不到,使用字符串前缀匹配最长的
xxxx/
├── image1
│ └── test.txt
├── img
│ └── test.txt
├── img2
├── t1.txt
│ └── test.txt
└── test.txt
nginx规则如下:
#规则A
location / {
root /var/www;
}
#规则B
location /img {
root /var/www/img;
}
#规则C
location ^~ /img/ {
root /var/www/img2;
}
#规则D
location ~* \/img\/ {
root /var/www/image1;
}
#规则E
location ~* \.txt {
root /var/www/image1;
}
验证:
http://localhost/image1/xxx
匹配规则A
http://localhost/img
匹配规则B
http://localhost/img/xxx/t.txt
匹配规则B
txt匹配规则
http://localhost/img1/xxx/t.txt
http://localhost/img1/xxx/t.txt?xxxx=aaa
http://localhost/img.txt
匹配规则E
http://localhost/test.txt
匹配规则A
http://localhost/img/test1.txt
匹配规则C当规则E不存在时
http://localhost/test.txt
http://localhost/test1.txt
http://localhost/t1.txt/test.txt
匹配规则F
http://nginx.org/en/docs/http/ngx_http_core_module.html#location
https://segmentfault.com/a/1190000009237425
https://blog.csdn.net/truong/article/details/49967393