路径问题

首先很常见的就是nginx的localtion路径问题. 以及代理目标的路径问题, 带/和不带会有区别.

例如

1
2
3
4
location ^~ /test/ {
proxy_pass https://your.domain/;
proxy_set_header Host your.domain;
}

其中 proxy_pass 字段后的url末尾是否带/会有区别.
下面直接用例子说明, 假设访问 your.domain/test/index.html 这个url, 不同的写法对应不同目标服务器上的结果.

location proxy_pass 结果
/test your.domain your.domain/test/index.html
/test your.domain/ your.domain//index.html
/test/ your.domain your.domain/test/index.html
/test/ your.domain/ your.domain/index.html

总结就是:
假设proxy_pass字段为str1, localtion字段为str2, 访问的路径为proxy.domain/yourPath.
如果str1末尾带路径(单个/也算), 则最终url为 str1 + (yourPath - str2)
如果str1末尾没路径, 则url为 str1 + yourPath

host问题

还是如上面的配置文件, proxy_set_header Host怎么写也会影响反向代理的效果

1
2
3
4
location ^~ /test/ {
proxy_pass https://your.domain/;
proxy_set_header Host your.domain;
}

假设客户端请求代理服务器A, A又反向代理到后端服务器B. 则如下表

变量 是否显示端口
$host 浏览器请求的ip, 即A域名/IP
$http_host 存在则显示 浏览器请求的ip和端口, 即A
$proxy_host 80端口否,其它是 被代理服务的ip和端口, 即B

目标网站问题

不仅是nginx配置的问题, 也有可能是需要代理的目标项目/网站问题.
例如:

  • 网站本身不支持或者有特殊校验,如open.spotify.com
  • 网站有自动跳转,如baidu.com跳转到www.baidu.com
  • 项目的前端资源路径为绝对路径, 比如引入css时写的"/css/“而不是”./css/", 在用路径区分反向代理(而不是域名)时会出资源404问题.
  • 网站用了CDN, 无法全代理

参考文章
https://blog.csdn.net/yihanzhi/article/details/107002881