DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决页面提示 Mixed Content: The page was loaded over HTTPS but requested insecure resource 修复

排查全站开启 HTTPS 后加载 HTTP 静态资源提示 Mixed Content 警告或被直接阻断,掌握 upgrade-insecure-requests 与全站相对协议重构。

问题现象

在全站升级为 HTTPS 后,浏览器地址栏的安全绿色小锁消失,变成黄色感叹号;或者某些外部脚本/API 无法加载:

Mixed Content: The page at 'https://example.com/home' was loaded over HTTPS, but requested an insecure script 'http://cdn.example.com/lib.js'. This request has been blocked; the content must be served over HTTPS.

或者图片提示被动混合内容警告:Mixed Content: ... was requested an insecure image ...。

触发根因

W3C 混合内容规范(Mixed Content Specification)为了保障传输安全:

  1. 安全降级防范:在一个已经由 HTTPS 加密的安全页面内部,严禁通过明文的非安全 http:// 协议去拉取资源,防止传输内容被中间人嗅探篡改;
  2. 主动混合内容(Active Mixed Content,如 JS、CSS、Iframe、API):浏览器一律强制直接拦截并阻止加载(Blockable Mixed Content);
  3. 被动混合内容(Passive Mixed Content,如图片、音视频):浏览器虽然允许加载,但会立即剥夺页面的安全认证状态,展示不安全警告。

解决步骤

1. 在服务端开启 CSP 自动升级不安全请求(一键全局修复)

在全站的响应头中配置 upgrade-insecure-requests 指令。该指令会通知现代浏览器:在请求页面引用的任何 http:// 资源时,在发起网络请求前在浏览器内部自动强行将协议替换为 https://:

在 Nginx 中配置:

add_header Content-Security-Policy "upgrade-insecure-requests;" always;

或者在 HTML 页面 <head> 中添加:

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

2. 将代码中的绝对协议链接重构为协议相对路径或纯绝对路径

修改前端代码与数据库中存储的历史图床 URL:

<!-- 错误写法: -->
<!-- <script src="http://cdn.example.com/app.js"></script> -->

<!-- 正确写法 1(明确指定 https): -->
<script src="https://cdn.example.com/app.js"></script>

<!-- 正确写法 2(协议自适应): -->
<script src="//cdn.example.com/app.js"></script>

3. 批量更新数据库中的历史富文本媒体外链

使用 SQL 将历史文章正文中的 http:// 批量安全替换为 https://:

UPDATE posts SET content = REPLACE(content, 'http://img.example.com', 'https://img.example.com');

验证确认

在浏览器中硬刷新页面并查看安全面板:

  • 地址栏完全呈现标准的绿色安全锁;
  • 控制台零 Mixed Content 警告,所有外部脚本与样式顺利完成 HTTPS 安全加载。