nginx 强制https 怎么做:从 301 跳转链路到 HSTS 的 8 步落地与排查(nginx 1.24/1.26 实测)
nginx 强制https 的标准做法是在 80 端口 server 块写一行 return 301 https://$host$request_uri;,nginx 默认不会自动跳转,必须显式配置。 nginx ≥1.25.1 用 http2 on; 替代 listen 443 ssl http2;,老写法在 1.25.1+ 会输出 the "listen ... http2" directive is deprecated 告警。 HSTS 不能替代 301:据 RFC 6797,HSTS 只对已成功访问过 https 的浏览器生效,首次 http 访问仍需 301 兜底。 SLB/CDN 卸载 TLS、回源走 80 时,$scheme 恒为 http,直接 return 301 会造成 ERR_TOO_MANY_REDIRECTS,需改用 $http_x_forwarded_proto 判断。 灰度期先上 302、稳定 7 天再换 301;HSTS 的 max-age 按 300 → 86400 → 604800 → 31536000 四档推进,每档观察一周。
为什么 http:// 还能直接打开?nginx 强制https 失效的 6 个根本原因
先看现象:一条 curl 就能判断问题在服务端还是浏览器缓存。
# -s 静默、-I 只看响应头;注意必须用 http:// 而不是 https://
$ curl -sI http://example.com | head -n 3
HTTP/1.1 200 OK
Server: nginx/1.24.0
如果第一行是 200 OK 而不是 301,就说明 80 端口的 server 块里根本没有 return 或 rewrite:nginx 默认不做任何协议升级,它会把请求照常交给 root 静态文件或 proxy_pass 的 upstream。所以问题在配置,不在浏览器。用 nginx -T 把 include 进来的配置全部展开核对:
# -T 打印完整生效配置(nginx 1.9.2+ 支持),grep 定位 80 端口块
$ nginx -T 2>/dev/null | grep -n -A6 'listen.*80'
$ nginx -v # nginx version: nginx/1.24.0
根因一:server 块“落错”了,请求根本没进你的配置。
# ❌ server_name 只有裸域,请求 Host 是 www.example.com 时不匹配
server {
listen 80;
server_name example.com;
}
同一台机器上多个站点都写 listen 80; 时,只有带 default_server 的块能接住未匹配的 Host;若谁都没写,nginx 按配置加载顺序取第一个 listen 80 的块。于是请求落到默认块,返回 404 或别的站点首页,nginx 强制https 自然不生效。server_name 的默认值是空字符串,别指望它兜底;改成 server_name example.com www.example.com; 或用 .example.com 通配。
根因二:指令写错,或漏了 permanent。
# ❌ 逻辑反了:只在已经是 https 时才跳
if ($scheme = https) { return 301 https://$host$request_uri; }
# ❌ 漏 permanent,rewrite 默认给 302,运维却按 301 缓存去排查
rewrite ^(.*)$ https://$host$1;
# ✅ 推荐写法:return 无正则开销,且明确 301
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
| 写法 | 状态码 | 是否默认 | 浏览器缓存 | 请求方法 |
|---|---|---|---|---|
return 301 |
301 | — | 持久缓存 | 常被改为 GET |
rewrite ... (无参数) |
302 | 是,默认 302 | 不缓存 | 保持 |
rewrite ... permanent |
301 | 否 | 持久缓存 | 常被改为 GET |
return 308 |
308 | — | 持久缓存 | 保持 POST |
根因三:CDN / 七层 SLB 把请求又打回 HTTP,形成跳转死循环。
CDN 已卸载证书、回源走 80 端口时,nginx 看到的 $scheme 恒为 http;此时再无条件下发 301,就是 301 → 回源 http → 再 301,Chrome 直接报 ERR_TOO_MANY_REDIRECTS。先确认链路:
# 看响应头里有没有 CDN 特征,判断 curl 打到的是源站还是边缘节点
$ curl -sI https://example.com | grep -iE 'server|via|x-cache|cf-ray'
# ✅ 回源仍为 HTTP 时的写法:信任代理层传来的协议头
map $http_x_forwarded_proto $is_https {
default 0;
https 1;
}
server {
listen 80;
if ($is_https = 0) {
return 301 https://$host$request_uri;
}
}
根因四:浏览器缓存了旧的 301。301 是永久重定向,Chrome 会持久保存直到手动清理。配置改完还跳旧地址,先用 curl -I(不经过浏览器缓存)和隐身窗口对比,即可区分服务端与客户端。
根因五:80 端口压根没监听或没映射。只写了 listen 443 ssl;,或 Docker 只 -p 443:443、防火墙只放通 443,请求被别的服务接走,检查 ss -lntp | grep ':80 '。
根因六:把 HSTS 当成 301 的替代品。据 Mozilla 文档,HSTS 只在浏览器已经通过 HTTPS 访问并收到 Strict-Transport-Security 头之后才生效,首次 http:// 访问仍必须靠 301 兜底;建议 max-age 起步 31536000(一年),申请 preload 需 63072000(两年)并配合 includeSubDomains。
不强制 HTTPS 的代价是实打实的:未加 Secure 的 Cookie 会随明文请求裸奔;而据 RFC 7540 §3.3,HTTP/2 通过 TLS 的 ALPN 协商(浏览器只实现 h2 over TLS),不跳 https 就用不上多路复用,首屏资源加载明显变慢。Let’s Encrypt 文档也明确建议所有 HTTP 请求以 301 指向 HTTPS 对应 URL,这也是后续配置 HSTS 与 OCSP Stapling 的前置条件。
nginx 强制https 完整实操步骤:从备份到灰度的 8 步
把 nginx 强制https 上线,最危险的不是写错 return 301,而是没有回滚依据、证书不覆盖 www、或者一上来就把 HSTS 的 max-age 拉到一年。下面 8 步按”先取证、再改、后灰度”的顺序落地,命令可直接复制,实测环境为 nginx/1.24.0 与 nginx/1.26.0(Ubuntu 22.04 / Rocky 9)。
第 1 步:记录基线。先确认版本,再把”当前真正生效的配置”整体导出——注意 nginx -T 会展开所有 include(conf.d、sites-enabled),这是回滚的唯一依据,直接备份单个 nginx.conf 是不够的。
# 确认版本,输出形如 nginx version: nginx/1.24.0
nginx -v
# 导出全部生效配置(含 include),文件名带日期便于回溯
nginx -T > /root/nginx.conf.bak.$(date +%F) 2>/root/nginx.T.stderr
# 校验导出是否完整:应能看到每个 server 块
grep -c "server {" /root/nginx.conf.bak.$(date +%F)
第 2 步:验证证书可用。证书缺 SAN 是”跳转后浏览器报证书名称不匹配”的头号原因,必须先查再看配置。
# 查看有效期、主体与 SAN;Let's Encrypt 证书有效期为 90 天
openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem
-noout -dates -subject -ext subjectAltName
# 期望输出包含:
# notAfter=Nov 12 08:00:00 2025 GMT
# X509v3 Subject Alternative Name:
# DNS:example.com, DNS:www.example.com
第 3 步:补全 443 块。证书链必须用 fullchain.pem(cert.pem 缺中间证书,部分安卓与旧客户端会报 unable to get local issuer certificate)。协议按 Mozilla Server Side TLS 的 intermediate 建议配置;nginx ≥ 1.25.1 起 listen ... http2 已废弃,改用独立的 http2 on; 指令。
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # 必须 fullchain
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3; # Mozilla intermediate,默认值仅 TLSv1.2 TLSv1.3(1.23.4+)
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
http2 on; # nginx ≥ 1.25.1 写法;1.24 仍用 listen 443 ssl http2;
}
第 4 步:改 80 块。$request_uri 保留原始路径与查询串,比 $uri 更安全(后者会丢掉 ?a=1)。
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://$host$request_uri; # 保留路径 + 查询串
}
第 5 步:处理多站点。同一 IP 上只允许一个 default_server,否则 nginx 启动直接报 a duplicate default server for 0.0.0.0:80。兜底块建议返回 444 直接断连,避免扫描器与未知 Host 落到业务站点被误跳转。
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444; # 不返回响应直接关闭连接,也不写 access.log
}
| 兜底策略 | 未知 Host 行为 | 日志 | 适用场景 |
|---|---|---|---|
return 444 |
直接断连 | 不记录 | 有公网 IP、被扫描较多(推荐) |
return 301 到主站 |
跳到主域名 | 记录 301 | 老域名统一收敛 |
return 404 |
正常响应 | 记录 404 | 需要保留审计痕迹 |
第 6 步:生效。先测再载,reload 平滑重载、不断活跃连接,restart 会掉连接。
nginx -t # 期望:syntax is ok / test is successful
systemctl reload nginx # 等价 nginx -s reload
第 7 步:观察 24 小时。统计 301 占比,并与 error.log 中的 499(客户端提前断开)、502 突增对照。
# 301 数量
awk '$9==301{c++} END{print c+0}' /var/log/nginx/access.log
# 80 端口总请求量,用于计算跳转覆盖率
awk '$0 ~ /:80 /{c++} END{print c+0}' /var/log/nginx/access.log
# 异常码突增排查
awk '$9==499||$9==502{c++} END{print c+0}' /var/log/nginx/error.log
第 8 步:加 HSTS(灰度)。稳定运行 7 天后再加,max-age 从 300 秒起步,逐步放大到 31536000;includeSubDomains 必须等所有子域都支持 https 再加,否则子域会直接不可访问,且浏览器在 max-age 内无法撤销。
add_header Strict-Transport-Security "max-age=300" always; # 灰度起点
# 一周后:max-age=86400;再一周:max-age=31536000; includeSubDomains
# always 保证 4xx/5xx 响应也带该头
常见追问:return 301 与 rewrite ^ https://$host$request_uri permanent 效果等价,但前者少一次正则匹配,优先用 return;若前面有 CDN 或负载均衡,需确认 $host 取自 Host 头而非回源 IP,否则会跳到内网地址。
nginx 强制https 配置示例:301 跳转、HSTS、IPv6 与反代场景
问:最小可用的强制跳转块长什么样?直接抄这一段即可(nginx 1.24 / 1.26 实测通过):
server {
listen 80;
listen [::]:80; # IPv6 必须单独写一行,否则 AAAA 记录解析过来会连不上
server_name example.com www.example.com;
return 301 https://$host$request_uri; # 保留原始路径与查询串
}
为什么用 $host$request_uri 而不是 $server_name$uri?$host 取自请求行或 Host 头并已做小写化与端口剥离,$request_uri 是未解码的原始 URI,二者拼接可让 /a/b?x=1 原样带到 https 侧;而 $uri 经过解码与规范化,查询串会丢。注意 $host 不含端口号——内网 8443 测试必须显式拼接,否则跳转后打到 443 直接连接失败:
return 301 https://$host:8443$request_uri;
问:443 块要写哪些参数才不算”裸奔”?
server {
listen 443 ssl;
http2 on; # nginx ≥ 1.25.1 用此指令;1.24 及更早写 listen 443 ssl http2;
server_name example.com www.example.com;
ssl_session_cache shared:SSL:10m; # 约可缓存 4 万条会话,默认 none
ssl_session_timeout 1d; # 默认 5m
ssl_protocols TLSv1.2 TLSv1.3; # 禁用 TLSv1/1.1(RFC 8996 已弃用)
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384; # Mozilla intermediate 列表
ssl_prefer_server_ciphers off; # 1.23.0 起默认 off,交给客户端选更优套件
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
always(nginx 1.7.5+)是关键:不加时 add_header 只在 2xx/3xx 生效,404、500 响应不带 HSTS 头,SSL Labs 一类检测工具会直接判为未启用。据 Let’s Encrypt 文档与 RFC 6797,首次上线建议先用 max-age=300 灰度,确认全站 HTTPS 无混合内容后再拉到 31536000。
| 指令 | 默认值 | 推荐值 | 影响 |
|---|---|---|---|
| ssl_session_cache | none | shared:SSL:10m | 10m≈4 万会话,省去重复握手 |
| ssl_session_timeout | 5m | 1d | 与 cache 大小需匹配,过长易挤占 |
| ssl_protocols | TLSv1.2 TLSv1.3(1.23.4+) | TLSv1.2 TLSv1.3 | 老版本默认含 TLSv1/1.1 |
| add_header … always | 无 | 加 always | 决定 4xx/5xx 是否输出 HSTS |
问:反代到后端要注意什么?在 location 中补两行,让后端识别真实协议;若后端(如 Spring Boot、Django)自己也开了强制跳转,会出现两次 301,建议只保留 nginx 这一层:
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme; # 后端据此判断原始协议
proxy_set_header X-Real-IP $remote_addr;
}
问:不想手写,certbot 能自动改吗?可以。certbot 2.x 执行下列命令后,会在 80 块内写入带 # managed by Certbot 注释的 if ($host = www.example.com) { return 301 https://$host$request_uri; },效果与手写 return 301 等价,只是条件判断更啰嗦:
certbot --nginx -d example.com -d www.example.com
--redirect --agree-tos -m ops@example.com --no-eff-email
# --redirect 即写入 301;改完记得 nginx -t && systemctl reload nginx
nginx 强制https 四种实现方式对比与选型表
先给结论:四种方式里,return 301 https://$host$request_uri; 写在 server 块是绝大多数站点的首选——它是 nginx 强制https 最省资源、语义最清晰的写法;只有需要正则捕获分组时才退而用 rewrite ... permanent;if ($scheme = http) 仅用于 80/443 合并的遗留配置;HSTS 不是跳转,而是跳转之后的加固层。
| 方式 | 指令 | 状态码 | 方法是否保留 | 适用场景 |
|---|---|---|---|---|
| return 301 | return 301 https://$host$request_uri; |
301 | 否(转 GET) | 绝大多数站点,首选 |
| rewrite permanent | rewrite ^ https://$host$request_uri permanent; |
301 | 否 | 需要正则捕获分组时 |
| if + return | if ($scheme = http) { return 301 ...; } |
301 | 否 | 80/443 混在同一 server 块 |
| HSTS | add_header Strict-Transport-Security ... |
无跳转 | — | 已全站 https 后的加固 |
# nginx 1.24 / 1.26 通用。return 指令自 0.8.42 起可用于 server 上下文
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
# 首选写法:server 级 return,$host 取请求行 Host(无则回退 server_name)
# $request_uri 保留原始路径+查询串,不参与解码,不会二次编码
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
# nginx 1.25.1 起 listen 的 http2 参数已废弃,改用 http2 on; 1.24 请写 listen 443 ssl http2;
http2 on;
server_name example.com www.example.com;
ssl_certificate /etc/nginx/ssl/example.com.fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# HSTS:max-age 无默认值,必须显式指定;always 参数需 1.7.5+
# 先从小值(如 300)灰度,确认无 http 子资源后再升到 31536000
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
需要保留原方法(POST/PUT)时把 301 换成 308,据 RFC 7538,308 明确定义为「永久重定向且不改变方法」,而 301 在 RFC 7231 中允许客户端把非 GET 请求改写为 GET——这是很多「表单提交后变空页面」问题的根因。灰度期请用 302,因为 301 会被浏览器长期缓存,撤回成本极高。
# 变体 A:需要捕获分组时(permanent = 301)
rewrite ^/old/(.*)$ https://$host/new/$1 permanent;
# 变体 B:需要保留 POST 等原方法
return 308 https://$host$request_uri;
# 变体 C:80/443 合并在同一 server 块(不推荐,SSL 配置与跳转逻辑耦合)
server {
listen 80;
listen 443 ssl;
server_name example.com;
if ($scheme = http) { # 注意:SLB 卸载 TLS 时 $scheme 恒为 http
return 301 https://$host$request_uri;
}
}
性能差异在哪:return 在 server rewrite 阶段直接结束请求,不进入 location 匹配、不做文件系统 stat,单核跑数万 QPS 的纯跳转毫无压力;rewrite ... permanent 要多走一次 PCRE 正则编译与匹配,功能等价但开销略高。能用 return 就别用 rewrite。另外把 return 误写进 http 块会直接报 nginx: [emerg] "return" directive is not allowed here,改配置后务必先跑 nginx -t。
HSTS 不能替代 301:据 RFC 6797 §5.2,浏览器必须先成功建立过一次 https 连接并读到该响应头,才会把后续 http 请求在本地改写成 https。首次访问、新设备、部分爬虫都覆盖不到,所以 HSTS 与 301 是叠加关系。同理,add_header 只在当前层级没有其他 add_header 时才继承上层,若在 location 里又写了 add_header,server 级的 HSTS 头会被悄悄丢掉——排查时用 curl -sI https://example.com | grep -i strict 验证。
边缘跳转 vs 源站跳转:在 CDN/SLB 上做 301 可省一次回源 RTT(同区域约 20–100 ms),但规则分散在多处、排障成本高。实践做法是边缘配一份、nginx 保留同规则兜底,两边行为保持一致,避免出现「边缘 301 到 https、源站又 301 回 http」的循环。
成本:Let’s Encrypt 证书免费、90 天自动续期;DV 证书约 0–300 元/年,OV 约 800–2000 元/年。nginx 强制https 本身零许可成本,真实投入是证书运维与改造工时,单站点通常 0.5–2 人时。
多层架构下 nginx 强制https 该放哪一层:SLB、CDN 与 Ingress
问:SLB 已经监听 443 并持有证书、回源走 80,nginx 里那句 return 301 https://$host$request_uri; 还要不要写?不能直接写。据 nginx 官方文档,$scheme 是”当前连接所用的协议”,在七层卸载(ALB/CLB、CDN 回源)场景下 SLB 与源站之间是明文 HTTP,nginx 看到的 $scheme 恒为 http。此时无条件 301 会把回源请求再次打回 https,SLB 又降级成 http 回源,形成 301 死循环:浏览器报 ERR_TOO_MANY_REDIRECTS,curl -I 能看到连续不断的 301 且 Location 始终相同。正确做法是先把 X-Forwarded-Proto 归一化成一个可判断的变量,再据此决策:
# /etc/nginx/conf.d/00-forwarded.conf (nginx 1.24.0 / 1.26.x 实测)
# map 必须放在 http 块内(conf.d/*.conf 默认即被 include 进 http 块)
map $http_x_forwarded_proto $real_scheme {
default "https"; # 头缺失时(如内网健康检查)按 https 处理,避免误跳
"http" "http"; # 精确匹配;不要写成 ~*http,正则不锚定会把 https 也匹配上
"~*^http(s*,|$)" "http"; # 兼容 "http, https" 这类多值头,默认值取第一个
}
server {
listen 80;
server_name example.com;
if ($real_scheme = "http") { # if 内只写 return / rewrite,见下方说明
return 301 https://$host$request_uri;
}
location / { proxy_pass http://app_backend; }
}
为什么 if 里不能顺手写 proxy_pass? nginx 官方 wiki 的著名条目 “IfIsEvil” 明确指出:if 在 location 内会创建一个嵌套的、配置不完整的 location,只有 return 和 rewrite(以及少数 set)是安全的。把 proxy_pass、try_files 塞进去,会出现请求体被丢弃、add_header 失效、error_page 不生效等难以复现的异常。需要按条件代理时,用 map 生成变量配合 proxy_pass $upstream,或用两个 server 块拆分。
| 架构层 | 证书持有方 | 这一层该不该做 301 | 关键配置 | 典型坑 |
|---|---|---|---|---|
| SLB 七层卸载 | SLB(ALB/CLB) | 否,交给 nginx 判断 | map $http_x_forwarded_proto |
$scheme 恒为 http,无条件 301 死循环 |
| CDN(Cloudflare 等) | 边缘节点 | 可开,但源站必须保留 | Always Use HTTPS(SSL/TLS → Edge Certificates) | 关闭代理(Grey Cloud)后站点回退明文 |
| Ingress-NGINX | Ingress 的 spec.tls Secret |
是 | force-ssl-redirect: "true" |
ssl-redirect 在无 TLS 段时静默不生效 |
| 应用层 | 无 | 仅作兜底,不要与 nginx 同开 | Spring Boot / Django 见下 | 两次 301,链路变长、日志重复 |
Kubernetes Ingress-NGINX 两个注解到底差在哪? nginx.ingress.kubernetes.io/ssl-redirect 默认为 true,但它仅在该 Ingress 配置了 spec.tls 段时才生效——很多人写完注解发现仍能走 http,就是因为漏了 tls 段。nginx.ingress.kubernetes.io/force-ssl-redirect: "true" 则忽略 TLS 段的存在,无条件跳转。据 ingress-nginx 官方注解文档,二者语义不同,混用(只写前者、以为无条件生效)是最常见的坑。
CDN 和应用层为什么都要”留一手”? Cloudflare 开启 Always Use HTTPS 后边缘直接返回 301,源站看似不需要配置;但一旦把记录切回 Grey Cloud 或有人直连源站 IP,明文立刻可达。同理,Spring Boot 的 server.forward-headers-strategy 默认值为 none,设为 framework 后才读取 X-Forwarded-Proto;Django 的 SECURE_SSL_REDIRECT 默认 False。这些只应作为兜底,与 nginx 同时开启会产生两次 301,链路变长且日志重复,建议只保留一层做决策。
怎么最快确认请求是在哪一层被降级成 http 的? 把两个变量写进日志格式,重载后看一条真实请求即可定位:
# 在 http 块内定义(nginx 1.24/1.26 通用)
log_format scheme_debug '$remote_addr "$request" '
'scheme=$scheme xfp="$http_x_forwarded_proto" '
'host=$host status=$status upstream=$upstream_addr';
access_log /var/log/nginx/access.log scheme_debug;
# 校验并热加载,不改连接
nginx -t && nginx -s reload
# 取证
tail -f /var/log/nginx/access.log | grep scheme_debug
若日志显示 scheme=http xfp="https",说明 TLS 已在 SLB 终止,nginx 侧必须靠 xfp 判断;若 xfp="" 而客户端确实是 https,说明 SLB 没有透传该头,需要在监听器上补加,否则 map 的 default https 会掩盖问题。后续与 HSTS(RFC 6797)配合时,Strict-Transport-Security 只应在确认整条链路都能稳定返回 https 的那一层下发,避免边缘已缓存 max-age 后源站回退明文导致全站不可访问。
常见错误与排查:nginx 强制https 之后出现的 6 类真实报错
排查 nginx 强制https 的报错,第一步永远是分清「谁在跳转」:是浏览器缓存了旧的 301、是 CDN/SLB 在边缘改写、还是 nginx 自己的 return 301 在循环。下面 6 类是 1.24/1.26 实测中最常撞到的,每条给出原始报错与可直接粘贴的命令。
1. 浏览器报 ERR_TOO_MANY_REDIRECTS,怎么快速定位是哪一跳在循环?
先只看跳转链,不要跟到底:
- HTTPS配置 · SSL证书安装服务(各种服务器)
- SSL证书安装服务 · 腾讯云 HTTPS 部署 · 证书过期更新
- NGINX / APACHE / TOMCAT / IIS 证书配置 · SSL证书安装
# -I 只取响应头,-L 跟随跳转,grep 出每一跳的 Location
curl -sI -L http://example.com | grep -i location
# 期望:Location: https://example.com/ 只出现一次
# 异常:Location: http://example.com/ (还是 http,说明判断反了)
若 Location 仍是 http:// 开头的同一地址,八成是 if ($scheme = https) 写反,或者前面有 CDN/SLB 回源走 80——此时 nginx 看到的 $scheme 恒为 http,于是它把已经 https 的请求又跳一次。临时插两行响应头直接看服务端认知:
# 放在 443 的 server 块内,排查完务必删除
add_header X-Debug-Scheme $scheme always; # nginx 与上游那一跳的协议
add_header X-Debug-Forwarded-Proto $http_x_forwarded_proto always; # CDN/SLB 透传的真实协议
若 X-Debug-Scheme: http 而 X-Debug-Forwarded-Proto: https,就该改用 $http_x_forwarded_proto 判断,或直接在 CDN 侧开「强制 HTTPS」。另外,301 会被浏览器长期缓存(据 RFC 9110 §15.4.2,301 默认可缓存),调试阶段建议临时用 307 或清缓存验证。
2. 报 400 Bad Request: The plain HTTP request was sent to HTTPS port 是什么原因?
这是客户端把明文 HTTP 打到了 443 端口,nginx 解析不出 TLS 握手。三个检查点:
ss -lntp | grep -E ':80|:443' # 确认 80 真在监听
nginx -T | grep -nE 'listen|server_name' # 确认 80 的 server 块没被注释
curl -sI http://example.com # 应返回 301,而不是 400
其余常见来源:SLB 端口映射误写成 80→443(应为 80→80、443→443),以及书签里写死了 https://example.com:80 这类畸形地址。
3. nginx: [emerg] unknown directive “http2” 怎么办?
http2 on; 这条独立指令是 1.25.1 才引入的(见 nginx CHANGES-1.25.1)。先用 nginx -v 确认版本,再按表选写法:
| nginx 版本 | 正确写法 | 行为 |
|---|---|---|
| 1.24.x 及更早 | listen 443 ssl http2; |
唯一可用写法 |
| 1.25.1 及以上 | listen 443 ssl; + 块内 http2 on; |
推荐;旧写法报 [warn] the "listen ... http2" directive is deprecated,不影响运行但污染 nginx -t 输出 |
4. nginx: [emerg] PEM_read_bio_X509_AUX() failed 是证书配错了吗?
报错含义是「这个文件不是可解析的 X.509 证书」——要么路径写错,要么把 privkey.pem 填进了 ssl_certificate。验证并修权限:
openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem -noout -subject
ls -l /etc/letsencrypt/live/example.com/ # live/ 是软链,指向 ../../archive/
# Let's Encrypt 的 archive/ 默认 700,nginx worker 常读不到;需让 worker 用户可进入该路径
chmod 755 /etc/letsencrypt/{live,archive} # 目录 755
chmod 600 /etc/letsencrypt/archive/example.com/privkey*.pem # 私钥 600
5. curl: (60) SSL certificate problem: unable to get local issuer certificate
典型的「只配了 cert.pem、漏了中间证书」。据 Let’s Encrypt 文档,应始终使用 fullchain.pem。检查链长:
openssl s_client -connect example.com:443 -servername example.com -showcerts /dev/null
| grep -c "BEGIN CERTIFICATE"
# 正常输出 2 或 3;输出 1 说明缺中间证书
6. 页面 301 成功,但图片/CSS 仍走 http、控制台报 Mixed Content
根因在 HTML 里写死的 http:// 绝对地址,与 nginx 无关。批量定位后先应急、再改根:
grep -rn "http://" /var/www/html --include="*.html" --include="*.css" --include="*.js"
# 应急:让浏览器自动把子资源升级到 https(CSP Level 3,现代浏览器均支持)
add_header Content-Security-Policy "upgrade-insecure-requests" always;
长期仍应改成协议相对(//cdn.example.com/a.js)或 https 绝对地址,否则 HSTS 生效前的首屏仍可能被降级劫持。
效果验证:5 种方法确认 nginx 强制https 真正生效
改完配置不重启、或者 server_name 没匹配上,都会让 nginx 强制https 看起来”配了但没生效”。下面 5 组命令按”单请求 → 跳转链路 → 响应头 → 协议版本 → 服务端日志”逐层收敛问题,命令在 nginx 1.24.0 与 1.26.1(OpenSSL 3.0.x、curl 8.x)上实测通过。
① 单请求验证:路径与查询参数是否原样保留
# -I 只看响应头,避免下载正文;路径与 ?a=1 是故意加的压力测试
curl -sI "http://example.com/path?a=1"
# 期望首行:HTTP/1.1 301 Moved Permanently
# 期望跳转头:Location: https://example.com/path?a=1
若 Location 变成 https://example.com/,说明规则里写的是 return 301 https://$host$uri;——$uri 是规范化后的路径,不含查询串,正确写法是 return 301 https://$host$request_uri;($request_uri 保留原始路径 + ?args)。硬编码首页地址是另一个常见错因。
② 链路验证:数清跳了几次
# -L 跟随跳转,-o /dev/null 丢弃正文,-w 只打印统计
curl -sI -L -o /dev/null
-w "%{http_code} %{num_redirects} %{url_effective}n"
http://example.com
# 期望:200 1 https://example.com/
%{num_redirects} 需 curl ≥ 7.12.3。大于 1 就是跳转链过长:典型场景是 http→https 一次、www 与非 www 又一次,SEO 上会把权重拆散,应合并为单条 return 301 或把 www 归并进同一个 server 块。
③ HSTS 头验证:看 200 与 404 两条路径
# 正常路径应有 HSTS 头
curl -sI https://example.com | grep -i strict-transport-security
# 期望:strict-transport-security: max-age=31536000; includeSubDomains
# 再打一个不存在的路径,验证 add_header 的 always 参数生效
curl -sI https://example.com/404notfound | grep -i strict
第二条命令若无输出,说明 add_header 漏了 always——nginx 默认只在 200/201/204/206/301/302/303/304/307/308 这些状态码上添加头,404/500 会被吞掉。这是 nginx 官方文档 ngx_http_headers_module 的明确行为。HSTS 语义见 RFC 6797,max-age=31536000 即一年,includeSubDomains 会连带所有子域,上线前务必确认子域都已具备 HTTPS。
④ TLS 版本验证:1.1 必须被拒
# 强制用 TLS 1.1 握手,应失败
curl -sI --tlsv1.1 --tls-max 1.1 https://example.com
# 期望报错:curl: (35) error:0A00042E:SSL routines::tlsv1 alert protocol version
# 1.2 / 1.3 应正常返回 200
curl -sI --tlsv1.2 --tls-max 1.2 https://example.com | head -1
curl -sI --tlsv1.3 https://example.com | head -1
error:0A00042E 是 OpenSSL 3.0 的错误码格式(旧版 1.1.1 显示为 tlsv1 alert protocol version)。能拒绝说明 ssl_protocols TLSv1.2 TLSv1.3; 已生效;--tls-max 需 curl ≥ 7.54。TLS 1.3 还需 ssl_ciphers 之外的 ssl_conf_command 配合才有意义,Mozilla SSL Configuration Generator 的 intermediate 配置可直接对照。
⑤ 日志验证:从服务端反查是否有漏网之鱼
# 统计状态码分布,看 301 数量是否与 http 入口流量吻合
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head
# 检查 80 端口是否仍有 200 直接响应(应为 0)
grep -c '" 200 ' /var/log/nginx/access.log
若 200 数量不为 0,多半是某个 location 里存在 return 200 或静态文件命中了未强制跳转的 server 块。
⑥ 外部工具:覆盖配置、响应头、协议三层
| 检查层 | 工具 | 判定标准 |
|---|---|---|
| 配置与证书 | Qualys SSL Labs | A+ 需同时具备 HSTS 与 TLS 1.3,缺一即 A |
| HSTS 预加载 | hstspreload.org | 显示 “example.com is on the HSTS preload list” |
| 实际协商协议 | Chrome DevTools → Network → Protocol 列 | 显示 h2(HTTP/2)而非 http/1.1 |
注意 HSTS 头在浏览器侧有”记忆性”:一旦收到过 max-age,后续 http 请求在浏览器内部就被改写为 https,本地测试会看不到 301——此时用 curl 或隐身窗口(仍需清 HSTS 缓存 chrome://net-internals/#hsts)验证才准确。
回滚、灰度与监控:nginx 强制https 上线后怎么不翻车
灰度为什么要从独立的 server_name 开始,而不是直接在主域名上放 5%?
因为 301 会被浏览器永久缓存,一旦错误跳转被写进客户端缓存,服务端改回来也没用——浏览器根本不会再来问第二次。所以先在 server_name test.example.com 的独立 server 块上跑满 48 小时,用真实流量验证证书链、http→https→最终域名的跳转链路和 HSTS 响应头,再动主域名。放量用 map 控制,同一份配置里切换 302/301:
# /etc/nginx/conf.d/force-https.conf (nginx 1.24.0 / 1.26.1 实测)
# map 必须放在 http 上下文;~* 为不区分大小写的正则匹配
map $http_user_agent $is_beta {
default 0;
"~*BetaTester" 1; # 灰度 UA 带标记;也可用 geo $is_beta 按内网 IP 段放量
}
server {
listen 80;
server_name example.com www.example.com;
set $redir_code 302; # 灰度期默认 302,随时可撤回
if ($is_beta) { set $redir_code 301; } # 5% → 50% → 100% 只改上面 map
return $redir_code https://$host$request_uri;
}
在 if 里只做 set 是 nginx 官方 wiki「IfIsEvil」明确认可的少数安全用法。每次 reload 前先打快照 cp -a /etc/nginx/nginx.conf /root/nginx.conf.bak.$(date +%F),回滚即反向覆盖:
cp -a /root/nginx.conf.bak.2025-03-01 /etc/nginx/nginx.conf
nginx -t # 期望:nginx: configuration file /etc/nginx/nginx.conf test is successful
systemctl reload nginx # reload 不断连接;只有改 listen 才需 restart
HSTS 的回滚代价远高于 301:一旦下发 max-age=31536000,浏览器一年内强制 https,只能等过期或让用户手动清缓存(Chrome 打开 chrome://net-internals/#hsts,在 Delete domain security policies 里删域名)。据 RFC 6797 第 6.1 节,UA 在 max-age 有效期内必须忽略任何降级到 http 的请求。生产按四档推进:
| 阶段 | max-age | 观察期 | 风险点 |
|---|---|---|---|
| 1 | 300(5 分钟) | 1 周 | 仅影响当前会话,几乎零成本 |
| 2 | 86400(1 天) | 1 周 | 确认所有子域都有有效证书 |
| 3 | 604800(7 天) | 1 周 | 此时才加 includeSubDomains |
| 4 | 31536000(1 年) | 长期 | 提交 preload 列表后不可逆 |
怎么提前发现跳转规则被误改?日志里带上 $scheme,才能区分「本来就走 https」和「被 301 过来的」:
# http 上下文
log_format main_ext '$remote_addr [$time_local] "$request" $status '
'$scheme $host "$http_user_agent"';
access_log /var/log/nginx/access.log main_ext;
用 nginx-prometheus-exporter 1.x 采集 stub_status,监控 nginx_http_requests_total{status="301"},告警阈值设为「5 分钟内 301 速率超过过去 1 小时均值 3 倍」——漏写 www 的 server_name、把 302 误改 301 这类事故都能在投诉前暴露。证书侧每月固定两条命令:
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null
| openssl x509 -noout -enddate
# 输出示例:notAfter=Jun 12 03:14:07 2025 GMT
certbot renew --dry-run # 每月一次,模拟续期,不消耗 Let's Encrypt 速率限制
变更留痕为什么必须记版本号?每次变更记录三项:nginx -v(如 nginx version: nginx/1.26.1)、nginx -t 完整输出、reload 时间戳。nginx 1.25.1 起 listen 443 ssl http2 中的 http2 参数被弃用、改为独立的 http2 on; 指令,若 1.26 的配置回退到 1.24,会直接报 nginx: [emerg] unknown directive "http2" in /etc/nginx/nginx.conf:42。是配置写错还是版本行为差异,只有留痕能 30 秒分清。
两者都返回 301,功能等价。return 在 server 上下文直接终止处理,不进入 location 匹配与正则,开销更低,是首选写法;只有需要捕获正则分组(如按路径改写域名)时才用 rewrite ^(.*)$ https://$host$1 permanent;。
先排除客户端缓存:用隐身窗口或 curl -I http://example.com 复测,curl 看到 301 而浏览器没有,说明是浏览器缓存了旧的 200 响应。其次检查 server_name 是否漏了 www 前缀,请求落到了 default_server 兜底块。
在 443 块临时加 add_header X-Debug-Scheme $scheme always;,看服务端认知的协议是 http 还是 https。若前面有 CDN 或 SLB 卸载了 TLS、回源走 80,$scheme 恒为 http,必须改用 if ($http_x_forwarded_proto = "http") 判断,而不是无条件 301。
不行。据 RFC 6797,HSTS 只对已经成功建立过 https 连接并读到该响应头的浏览器生效,首次访问、新设备、部分爬虫仍会走明文 http。正确顺序是先 301 兜底,稳定运行后再叠加 HSTS 做加固。
不会。301 是永久重定向,Google 明确表示会把原 URL 的权重与索引迁移到目标地址。关键有两点:保持路径 1:1 映射(不要把所有页面都跳到首页),以及确保跳转后返回 200 且证书链完整。
本质相同。certbot 2.x 在 –redirect 模式下会往 80 端口块写入带 # managed by Certbot 注释的 if ($host = …) { return 301 …; },效果与手写 return 301 一致;区别是手写更简洁、不会被 certbot 的续期逻辑覆盖。
建议开。主流浏览器只在 TLS 连接上启用 HTTP/2(RFC 7540 §3.3),不强制 https 就用不上多路复用。nginx ≥1.25.1 用 http2 on;,1.24.x 及更早版本写 listen 443 ssl http2;,改完用 curl -sI –http2 https://example.com 确认协议协商结果。
本文由 sslgood.com 安全团队基于生产环境实战经验撰写,关键结论均经过技术复核。