解决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;要加,不然会有时候成功,有时候失败。

总结

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

相关推荐
|晴 天|5 小时前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript
猫3286 小时前
v-cloak
前端·javascript·vue.js
旷世奇才李先生6 小时前
Vue 3\+Vite\+Pinia实战:企业级前端项目架构设计
前端·javascript·vue.js
SoaringHeart8 小时前
Flutter进阶:用OverlayEntry 实现所有弹窗效果
前端·flutter
IT_陈寒10 小时前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace10 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常10 小时前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o10 小时前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端10 小时前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
lar_slw10 小时前
k8s部署前端项目
前端·容器·kubernetes