HTTPS页面加载HTTP资源报错解决方案:Nginx代理实践

5 阅读1分钟

一、问题现象 当HTTPS页面中通过XMLHttpRequest请求HTTP资源时,浏览器会抛出Mixed Content错误,阻断非安全内容加载。典型报错信息: MixedContent: The page at 'https://xxx' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://xxx'

二、核心原因

  • 协议冲突:HTTPS安全页面内嵌HTTP非安全资源,形成混合内容
  • 安全策略:现代浏览器默认阻止HTTP资源加载,防止中间人攻击
  • 特殊场景:私有云内网服务无法提供HTTPS协议支持

三、解决方案

方案1:强制HTTPS
直接修改资源链接为HTTPS协议(如http://xxxhttps://xxx

适用场景

:第三方服务支持HTTPS协议

方案2:CSP策略升级
在HTML头部添加策略自动升级请求:

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

适用场景

:可控的第三方HTTP资源

方案3:Nginx代理转发(推荐)
通过SSL代理服务中转HTTP请求

改造要点

  1. 原始HTTP链接:http://192.168.0.1:8080/rtc/webrtc/play?app=live
  2. 代理后HTTPS链接:
    https://proxy.com.cn:15454/rtc/webrtc/play?app=live&X-Proxy-Target=192.168.0.1:8080
  3. 配置Nginx代理:
    1.  server {
       listen 15454 ssl;
       listen [::]:15454 ssl;
       
       ssl_certificate /etc/nginx/ssl/proxy.com.cn.pem;
       ssl_certificate_key /etc/nginx/ssl/proxy.com.cn.key;
       ssl_protocols TLSv1.2 TLSv1.3;
       ssl_ciphers HIGH:!aNULL:!MD5;
       
       server name proxy.com.cn;
       
       location / {
           set $target ""
           #用正则从args中提取,不区分大小写
           if ($args ~* "x-proxy-target=([^&]+)"){
               set $target $1;
           }
       
           if ($target ''){
               return 400 '{"code":400,"msg":"Missing x-proxy-target"}';
           }
       
           resolver 8.8.8.8 114.114.114.114 va1id=300s;
           resolver timeout 5s;
       
           proxy_pass http://$target$request_uri;
           proxy_http_version 1.1;
           proxy_set_header Host $target;
           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 $scheme;
           proxy_set_header Connection ""
           proxy_connect_timeout 10s;
           proxy_read_timeout 60s;
           }
       }
      

注意事项

  • 代理服务器需配置有效的SSL证书
  • 内网地址建议通过参数加密传输
  • 设置合理的proxy_connect_timeout避免阻塞