问题背景:
需要在一个http的web服务中直接跟另一个https服务交互,不经过自身后端。
又来到了熟悉的跨域访问问题。
解决逻辑就是使用nginx转发,涉及到的文件也就是nginx.conf文件,前面解决minio链接时已经有经验了,但没想到这次的跨域问题还是折腾了我好几个小时,记录一下。
解决方式
配置nginx转发服务, 增加https服务的转发。
这次我没有像解决minio链接里那样改写请求路径,直接使用了https原本的uri。
c
# nginx.conf
upstream httpsService {
server https-service.com:443;
}
server {
listen 80;
server_name _;
access_log /xx/xx/access.log full_proxy_log;
location /api/openApi {
proxy_pass https://httpsService ;
proxy_set_header Host https-service.com;
}
....
}
如果转发还是报错,修改nginx的日志打印格式,看看是host问题还是uri问题。
c
access_log /xx/xx/access.log full_proxy_log;
其中的full_proxy_log
是我新增的日志格式。完整内容如下:
c
# nginx配置入口文件,跟上面的不是同一个哈
http {
...
log_format full_proxy_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'-> $upstream_addr$request_uri';
....
}
日志输出示例:
c
10.30.115.58 - - [18/Jul/2025:22:16:22 +0800] "POST /api/openApi/token HTTP/1.1" 200 460 "-" "PostmanRuntime/7.44.1" -> xx.xx.xx.xx:443/api/openApi/token
踩坑点
1.server https-service.com:443;
这里的端口
一定要带上,否则nginx默认会转发到80端口。即使你在proxy_pass中使用了https
。
2.proxy_set_header Host https-service.com;
要加,不然会有时候成功,有时候失败。
总结
遇到错误要冷静分析日志,日志不详细就要想办法加,而不是像无头苍蝇一样乱试。