今天访问网站的一个链接 https://so.sztcrs.com/api 突然发现访问不了,被重定向到了个错误地址https://so.sztcrs.com:9443/api
因为我现在网站使用的是caddy 作为反向代理服务器,目标服务器为nginx ,突然出现这样的情况,也没动过配置。
不知道问题出在哪,打开curl调试下吧。
curl -I https://so.sztcrs.com/api
HTTP/1.1 301 Moved Permanently
Alt-Svc: h3=":443"; ma=2592000
Content-Length: 162
Content-Type: text/html
Date: Sat, 13 Jul 2024 05:54:53 GMT
Location: https://so.sztcrs.com:9443/api/
Server: Caddy
Server: nginx
Strict-Transport-Security: max-age=31536000
显示301重定向到了 Location: https://so.sztcrs.com:9443/api/ ,这明显是不对的。
网上查了下资料,影响nginx 301重定向的 3个参数 absolute_redirect server_name_in_redirect port_in_redirect
这里顾名思义,port_in_redirect因为它默认是没问题,这里暂不分析absolute_redirect on
: 绝对重定向 默认开启absolute_redirect off
: 相对重定向 ,嗯这个有点靠谱了,nginx 配置http节点加上这个再试试curl
curl -I https://so.sztcrs.com/api
HTTP/1.1 301 Moved Permanently
Alt-Svc: h3=":443"; ma=2592000
Content-Length: 162
Content-Type: text/html
Date: Sat, 13 Jul 2024 06:14:04 GMT
Location: /api/
Server: Caddy
Server: nginx
Strict-Transport-Security: max-age=31536000
显示location到了相对目录/api/,浏览器访问也正常了,地址是:https://so.sztcrs.com/api/
另外再调试了一下server_name_in_redirect
通过它虽然也能解决问题,但是我这种情况:反代跟目标服务不在同一台服务器,且目标服务器使用的非默认ssl端口
用这个参数解决这种问题就要把nginx网站配置文件的server_name so.cdn.sztcrs.com so.sztcrs.com; server_name第一个域名必须是能访问到真实服务器的解析域名。
因为在server_name_in_redirect on
的情况下,nginx会301到配置文件中server_namer的第一个域名,我的就是下面这种情况:
curl -I https://so.sztcrs.com/api
HTTP/1.1 301 Moved Permanently
Alt-Svc: h3=":443"; ma=2592000
Content-Length: 162
Content-Type: text/html
Date: Sat, 13 Jul 2024 06:25:15 GMT
Location: https://so.cdn.sztcrs.com:9443/api/
Server: Caddy
Server: nginx
Strict-Transport-Security: max-age=31536000
看到没,location到了nginx网站配置server_name so.cdn.sztcrs.com so.sztcrs.com;
的第一个域名, https://so.cdn.sztcrs.com:9443/api/ 这是真实的目标服务器地址,可以访问,可是非常丑,我这里要把so.sztcrs.com置前,变成这样:nginx网站配置server_name so.sztcrs.com so.cdn.sztcrs.com;
location的地址就会变成不能访问的https://so.sztcrs.com:9443/api/ ,这显然是不行的。
啰嗦这么多,只想说,具体原因真得具体分析。这里记录并分享一下吧,nginx默认配置在作为反向代理目标服务器中的一个大坑
[missing note]第二个坑:不能获取来访客服真实IP,显示的全是反向代理服务器的IP※
这个没什么好调试的了,查阅资料,在nginx配置文件http节点加上:
#获取反代或CDN后的真实访问客户IP
set_real_ip_from 0.0.0.0/0;
real_ip_header X-Forwarded-For;
这里纯作记录分享了。