在nginx的location中配置proxy_pass时,当在后面的url上加不加”/“,区别是如此的大呢。此文详解nginx的location、proxy_pass带”/“和不带”/“的区别。
首先我们先讲讲,location 带"/"
和不带"/"
的区别。
如果在location末尾加上了”/“,相当于是绝对根路径,则nginx不会把location中匹配的路径部分去走代理;
如果没有加”/“,则会把匹配的路径部分也给代理走。
Location的目录匹配示例详解:
- 没有”/“时,可以模糊匹配字符串本身和后面所有
例如:
1 | server |
可以匹配如下几种请求:
- 访问
http://127.0.0.1/abc/defghi
, 实际访问的是/usr/share/nginx/abc/defghi 文件; - 访问
http://127.0.0.1/abc/def/ghi
,实际访问的是/usr/share/nginx/abc/def/ghi 文件; - 访问
http://127.0.0.1/abc/def/
,实际访问的是/usr/share/nginx/abc/def/index.html文件; - 访问
http://127.0.0.1/abc/def/ghi/
,实际访问的是/usr/share/nginx/abc/def/index.html文件;
- 而有”/“时,只能匹配后面,例如:
1 | server |
可以匹配如下几种请求:
- 访问
http://127.0.0.1/abc/def/ghi/
,实际访问的是/usr/share/nginx/abc/def/ghi/index.html 文件 - 访问
http://127.0.0.1/abc/def/ghi
,实际访问的是/usr/share/nginx/abc/def/ghi 文件 - 访问
http://127.0.0.1/abc/def/
,实际访问的是/usr/share/nginx/abc/def/index.html文件
Proxy_pass后url区别详解
下面四种情况分别用http://127.0.0.1/archives/
进行访问。
第一种:proxy_pass加”/“
1
2
3
4location /archives/ {
proxy_pass https://www.thexqf.top/;
}
结论:会被代理到https://www.thexqf.top/这个url第二种: proxy_pass不加”/“
1
2
3
4location /archives/ {
proxy_pass https://www.thexqf.top;
}
结论:会被代理到https://www.thexqf.top/archives/ 这个url第三种: 加目录加”/“:
1
2
3
4location /archives/ {
proxy_pass https://www.thexqf.top/about/;
}
结论:会被代理到https://www.thexqf.top/about/这个url。第四种:加目录不加”/“:
1
2
3
4location /archives/ {
proxy_pass https://www.thexqf.top/about;
}
结论:会被代理到https://www.thexqf.top/about这个url
总结
location目录字符串后加
/
,就只能匹配后面,不加不仅可以匹配后面还可字符串模糊匹配,类似str*。proxy_pass加
/
, 代理地址就不加location匹配目录; 不加/
,代理直接就加目录。