路径问题

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

例如

nginx
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 怎么写也会影响反向代理的效果

nginx
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