负载均衡将https请求转发后端http服务报错:The plain HTTP request was sent to HTTPS port

https请求报错:The plain HTTP request was sent to HTTPS port


示例背景描述:

  • www.test.com:11001服务需要对互联网使用https提供服务
  • 后端java服务不支持https请求,且后端程序无法修改,仅支持http请求

问题描述:

报错如下:

解决思路:通过nginx代理

此处暂时将后端服务器设定为192.168.1.1,具体配置如下:

bash 复制代码
server {
    listen 11001;
    server_name  localhost;

    location / {
        proxy_pass http://192.168.1.1:11001/;
        proxy_set_header Host $host:$server_port; # 包含端口号防止丢失
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https; # 强制设置协议为 HTTPS
        proxy_set_header X-Forwarded-Port $server_port;  # 传递端口

        # 重定向修正
        proxy_redirect ~^(http://[^:/]+)(:([0-9]+))?/(.*)$ https://$host:$server_port/$4;
        proxy_redirect ~^(http://)([^/]+)/(.*)$ https://$host:$server_port/$3;

        # 可选:日志调试
        access_log /var/log/nginx/redirect_fix.log main;
        error_log /var/log/nginx/redirect_error.log debug;

		# 可选配置
        proxy_connect_timeout 60s;
        proxy_read_timeout 60s;
    }

	# 可选配置
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

}

关键配置说明

1、proxy_redirect 正则表达式​:

bash 复制代码
proxy_redirect ~^(http://[^:/]+)(:([0-9]+))?/(.*)$ https://$host:$server_port/$4;

2、​备用规则​:​

bash 复制代码
proxy_redirect ~^(http://)([^/]+)/(.*)$ https://$host:$server_port/$3;

3、​强制协议头部​:

bash 复制代码
proxy_set_header X-Forwarded-Proto https;
  • 即使后端服务不使用这个头部,也设置它以保持一致性

测试与验证方法
1、测试配置:

bash 复制代码
nginx -t

2、重载配置:

bash 复制代码
nginx -s reload

3、监控日志:

bash 复制代码
tail -f /var/log/nginx/access.log 
tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/redirect_fix.log
tail -f /var/log/nginx/redirect_error.log

4、重新访问测试

https://www.test.com:11001


常见问题排查表

问题现象 可能原因 解决方案
重定向循环 后端服务也尝试重定向 检查后端响应是否已经是HTTPS
端口号不正确 正则匹配失败 添加更通用的匹配规则
HTTPS证书错误 证书不匹配 检查SLB证书是否有效
404 错误 路径被修改 检查正则中的路径捕获组 如 4 和 3

如果上述配置仍有问题,使用这个更强大的版本:

bash 复制代码
proxy_redirect ~^http(://[^/]+)?(:\d+)?/(.*)$ https://$host:$server_port/$3;
proxy_redirect ~^http(://)([^/]+)/(.*)$ https://$host:$server_port/$3;
proxy_redirect default;

这个规则会:

  • 匹配任何以 http 开头的重定向
  • 替换为 https + 原始域名 + 11001端口
  • 保留原始路径不变

最后我想说:请不要以此视为定论,这只是我的个人经验

相关推荐
小马同学-2 小时前
负载均衡-LVS全解析
运维·负载均衡·lvs
IPdodo跨境网络4 小时前
HTTP 与 SOCKS5 代理到底差在哪?用 Node.js 跑一次连接链路对比
http
小小龙学IT4 小时前
gRPC 开源高性能 RPC 框架深度解析:从 HTTP/2 到跨语言微服务实战
http·rpc·开源
CDN3605 小时前
俄语区跨境站点优化实战:CDN+Nginx 解决 H5 白屏、交互延迟、链路卡顿问题
运维·nginx·交互·h5 加速·nginx 轻交互调优
難釋懷6 小时前
Nginx重试机制
运维·nginx
2501_916007471 天前
Bundle ID 注册与管理 App ID 创建指南 命名规则 权限开关与删除注意事项
android·ios·小程序·https·uni-app·iphone·webview
国际云,接待1 天前
Nginx 后面接负载均衡,502/504 到底该先查哪里?
运维·nginx·负载均衡
刘某的Cloud1 天前
Galera Cluster部署 mariadb 节点down机,log sequence number恢复
linux·运维·数据库·负载均衡·mariadb·集群·高可用
二宝哥1 天前
CentOS 7.9 离线安装 Nginx 并配置openssl1.1.1
linux·nginx·centos
Misnearch1 天前
MCP以及底层协议、传输模式
http·mcp·json-rpc