解决http的web服务中与https服务交互的问题

问题背景:

需要在一个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;要加,不然会有时候成功,有时候失败。

总结

遇到错误要冷静分析日志,日志不详细就要想办法加,而不是像无头苍蝇一样乱试。

相关推荐
炫饭第一名1 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫2 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊2 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter2 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折2 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_2 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial2 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu3 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端
jiayu3 小时前
Angular6学习笔记13:HTTP(3)
前端
小码哥_常3 小时前
Kotlin抽象类与接口:相爱相杀的编程“CP”
前端