HTTP/2 与 HSTS
约 669 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › HTTPS 与 TLS(在新窗口打开) › HTTP/2 与 HSTS
HTTP/2 配置
HTTP/2 在 Nginx 1.9.5+ 中支持,只需在 listen 后加 http2:
server {
listen 443 ssl http2; # 开启 HTTP/2
server_name example.com;
ssl_certificate /etc/ssl/certs/example.crt;
ssl_certificate_key /etc/ssl/private/example.key;
# 其余配置不变
root /var/www/html;
location / {
try_files $uri $uri/ =404;
}
}检查 HTTP/2 是否生效
# curl 查看 HTTP 版本
curl -I --http2 https://example.com
# HTTP/2 200
# 查看响应头中的 ALPN 协商结果
curl -v --http2 https://example.com 2>&1 | grep "ALPN"
# ALPN, server accepted protocol h2HTTP/2 核心优势
| 特性 | HTTP/1.1 | HTTP/2 |
|---|---|---|
| 多路复用 | ❌(一个 TCP 一次只能处理一个请求) | ✅ 单一连接并发多请求 |
| 头部压缩 | ❌(明文传输 Header) | ✅ HPACK 压缩(减少约 80%) |
| Server Push | ❌ | ✅(服务端主动推送资源) |
| 二进制协议 | ❌(文本协议) | ✅(二进制、更高效) |
| 安全要求 | 可选 | 非强制但主流浏览器仅支持 HTTPS 的 h2 |
HSTS(HTTP Strict Transport Security)
HSTS 告诉浏览器:以后只能通过 HTTPS 访问该域名。
server {
listen 443 ssl http2;
server_name example.com;
# 启用 HSTS(有效期 2 年)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
}| 参数 | 含义 |
|---|---|
max-age=63072000 | 有效期(秒),2 年 |
includeSubDomains | 子域名也强制 HTTPS |
preload | 申请加入浏览器 HSTS Preload 列表 |
always | 即使 4xx/5xx 也发送此头 |
HSTS Preload
# 提交域名到 HSTS Preload 列表
# 访问:https://hstspreload.org/加入 preload 列表后,浏览器在首次安装时就内置该域名必须使用 HTTPS,彻底杜绝 HTTP 访问。
add_header always 的作用
# 不加 always:错误页面不会发送此头
add_header X-Frame-Options SAMEORIGIN;
# 加 always:所有响应(包括 4xx/5xx)都发送
add_header X-Frame-Options SAMEORIGIN always;综合配置
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.crt;
ssl_certificate_key /etc/ssl/private/example.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# HSTS(2 年 + 子域名)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
# 其他安全头
add_header X-Content-Type-Options nosniff always;
add_header X-Frame-Options DENY always;
add_header X-XSS-Protection "1; mode=block" always;
root /var/www/html;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP → HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}小结
- HTTP/2 只需在
listen后加http2即可开启,大幅提升页面加载性能。 - HSTS 强制浏览器 HTTPS 访问,
max-age=63072000; includeSubDomains常用配置。 add_header always确保安全头在错误响应中也发送。- HSTS Preload 将域名硬编码到浏览器,最高级别的 HTTPS 强制。
- HTTP/2 需要 HTTPS 配合(主流浏览器实现),建议一并开启。
上一节:SSL 证书与 HTTPS 配置 下一节:rewrite 与 return
