在nginx中配置proxy_pass时,如果在proxy_pass后面的url加(/斜杆+[任意字符]),相当URL路径替换匹配到的路径(字符串替换),则nginx不会把location中匹配的路径部分代理走;如果没有/,则会把匹配的路径部分给代理走。
下面五种情况分别用http://127.0.0.1:84/abc/index.html进行访问。
配置完整信息(只是展示一个样例,全部内容和和拼接的URL看后面文章)
server
{
listen 83;
server_name 127.0.0.1;
root /etc/nginx/conf.d/demo;
}
server
{
listen 84;
server_name rdtest.lyndemo.com;
location /abc
{
proxy_pass http://127.0.0.1:83/linux;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
其中/etc/nginx/conf.d/demo路径下的index.html内容如下
浏览器访问:http://127.0.0.1:84/abc/index.html
测试结果:
//----------端口后不带/字符,表示衔接location全部URI路径
情况一:
location /abc
proxy_pass http://127.0.0.1:83;
页面结果:abc index
url拼接结果:http://127.0.0.1:83/abc/index.html
//----------端口后带/字符或者/[任意字符],替换location指定的字符
情况二:
location /abc
proxy_pass http://127.0.0.1:83/;
页面结果:home index
url拼接结果:http://127.0.0.1:83/index.html
情况三:
location /abc
proxy_pass http://127.0.0.1:83/linux/;
页面结果:linux index
url拼接结果:http://127.0.0.1:83/linux//index.html
情况四:
location /abc
proxy_pass http://127.0.0.1:83/linux;
页面结果:linux index
url拼接结果:http://127.0.0.1:83/linux/index.html
情况五:
location /abc/
proxy_pass http://127.0.0.1:83/linux;
页面结果:404 not found
url拼接结果:http://127.0.0.1:83/linuxindex.html(体现了是字符替换的结果,源码没看,只是猜测,URL是根据nginx错误日志发现的路径)
情况六:
location /abc/
proxy_pass http://127.0.0.1:83/linux/;
页面结果:linux index
url拼接结果:http://127.0.0.1:83/linux/index.html