HTTPS = HTTP over TLS/SSL,通过 混合加密体系 解决三大问题:
// 前端感知的典型场景:混合内容拦截
// 在 HTTPS 页面加载 HTTP 资源会被浏览器拦截
// 控制台报错:Mixed Content: The page was loaded over HTTPS...
客户端发送:
# 开发者工具查看加密套件(Chrome)
chrome://flags/#tls13-variant
服务端回应:
// 前端可通过 JS 获取证书信息(需要用户授权)
navigator.mediaDevices.getUserMedia({ video: true })
.then(() => {
const cert = document.querySelector('video').getCertificate();
console.log(cert.issuer); // 颁发机构
});
客户端验证证书:
// 开发环境常见错误:自签名证书报错
// 解决方案1:浏览器手动信任(危险)
// 解决方案2:配置本地CA(推荐使用 mkcert)
// 生成本地证书
$ mkcert -install
$ mkcert localhost 127.0.0.1 ::1
# 简化版密钥计算逻辑(实际为二进制操作)
client_random = 0x1234
server_random = 0x5678
pre_master = ecdhe(client_params, server_params)
master_secret = PRF(pre_master, client_random + server_random)
双方用 Master Secret 生成对称密钥,后续通信使用对称加密。
nginx
# Nginx 配置自动跳转(301 永久重定向)
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
html
javascript
// 设置 Secure + HttpOnly + SameSite
document.cookie = `session=xxx; Secure; HttpOnly; SameSite=Lax`;
nginx
# 添加 Strict-Transport-Security 头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
提交预加载列表
复用 TLS 会话减少握手耗时:
nginx
# Nginx 配置会话票证
ssl_session_tickets on;
ssl_session_timeout 1d;
由服务端缓存证书状态,减少客户端验证耗时:
nginx
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8;
比 TLS 1.2 减少一次 RTT:
nginx
ssl_protocols TLSv1.3 TLSv1.2;
现象:Android 低版本报错,iOS 正常
解决:使用 openssl
补全证书链
bash
$ openssl s_client -showcerts -connect example.com:443
$ cat fullchain.pem > chained.crt # 合并根证书和中间证书
定位:使用 CSP 报告收集非 HTTPS 请求
html
检测工具:
bash
$ curl -I https://example.com # 检查 Server 头
$ nscurl --ats-diagnostics https://example.com # iOS 特性检测
javascript
// webpack.config.js
const fs = require('fs');
const https = require('https');
module.exports = {
devServer: {
https: {
key: fs.readFileSync('localhost-key.pem'),
cert: fs.readFileSync('localhost.pem')
},
public: 'https://localhost:8080' // 避免浏览器警告
}
};
javascript
// sw.js 中捕获证书错误
self.addEventListener('fetch', event => {
if (event.request.url.startsWith('https://')) {
event.respondWith(
fetch(event.request).catch(err => {
console.error('证书错误:', err);
return new Response('HTTPS故障');
})
);
}
});
bash
# 一键检测(需安装 testssl.sh)
$ testssl.sh --color 0 example.com
通过理解 TLS 握手流程,前端开发者能更好地处理证书错误、优化资源加载策略,并推动全站安全升级。记住:HTTPS 不是终点,而是现代 Web 应用的起跑线。