官方说明:在nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。

一般proxy_pass后面有四种情况:ip:端口ip:端口/ip:端口/上下文ip:端口/上下文/下面我就这四种情况进行举例说明。
例如访问地址:http://192.168.2.39:8081/hussarApi/test/getList

1、ip:端口

location /hussarApi/ {
	proxy_pass http://192.168.2.188:8280;	
}

代理地址:http://192.168.2.188:8280/hussarApi/test/getList
//url后无/,为相对路径,连同匹配部分hussarApi也追加到代理地址上

2、ip:端口/

location /hussarApi/ {
	proxy_pass http://192.168.2.188:8280/;	
}

代理地址:http://192.168.2.188:8280/test/getList
//url后有/,为绝对根路径,会将hussarApi部分去掉,代理地址拼接hussarApi后面路径

3、ip:端口/上下文

location /hussarApi/ {
	proxy_pass http://192.168.2.188:8280/hussarApi;	
}

代理地址:http://192.168.2.188:8280/hussarApitest/getList
//url后有上下文,会将访问地址hussarApi去掉,代理地址直接拼接访问地址hussarApi后面路径

4、ip:端口/上下文/

location /hussarApi/ {
	proxy_pass http://192.168.2.188:8280/hussarApi/;	
}

代理地址:http://192.168.2.188:8280/hussarApi/test/getList
//url后有上下文,会将访问地址hussarApi去掉,代理地址直接拼接访问地址hussarApi后面路径

34的差别在于proxy_pass url后面加了上下文地址,不带/和带着/两种情况,代理规则是一样的,都是取匹配部分后面的地址进行拼接,所以如果proxy_pass url端口后面带着上下文的,统一在最后面添加/

注意:location 为正则表达式的时候2不能使用
location 正则情况,url后面不能加 /

location ~ /hussarApi/ {
	proxy_pass http://192.168.2.188:8280/;
}

location 非正则情况,可以添加/

location /hussarApi/ {
	proxy_pass http://192.168.2.188:8280/;
}

特别鸣谢大神贴:https://blog.csdn.net/u010433704/article/details/99945557

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐