nginx 强制 https 跳转怎么做:301、308、反向代理与 CDN 场景的完整配置和排错
在 nginx 1.24/1.26 中,80 端口 server 块写 listen 80 default_server; server_name example.com www.example.com; return 301 https://$host$request_uri; 即可完成 nginx 强制 https 跳转,301 会被浏览器缓存,调试期建议先用 302。 return 301 在 server 级直接结束请求,比 rewrite ^ https://$host$request_uri permanent; 少一次正则匹配;据 nginx 官方文档,能用 return 时优先用 return。 反向代理或 CDN 终止 TLS 时,源站 nginx 看到的是 http,需用 map $http_x_forwarded_proto $forwarded_scheme 判断,并只信任来自负载均衡网段的 X-Forwarded-Proto。 验证命令:curl -I http://example.com/path?a=1 应返回 HTTP/1.1 301 与 Location: https://example.com/path?a=1;curl -I -L --max-redirs 3 可快速发现跳转循环。 HSTS 不是跳转:据 RFC 6797,Strict-Transport-Security 只在浏览器收到 HTTPS 响应后生效,首次 http 访问仍依赖 nginx 强制 https 跳转。
一、http 访问为何没跳到 https:nginx 强制 https 跳转的根因与判断顺序
问:域名已经配好证书,浏览器打开 http://example.com 却还是明文页面,nginx 到底在哪一步“没跳”?
先别改配置。nginx 强制 https 跳转不生效,九成不是 return 301 写错了,而是这条规则根本没被执行到——请求压根没进到你写 return 的那个 server 块。按下面的顺序从外到内排查,每一步都有明确的判据。
# 1) 看客户端实际收到什么:状态码、Location 是否指向 https
curl -I http://example.com
# 期望:HTTP/1.1 301 Moved Permanently
# Location: https://example.com/
# 若返回 200,说明跳转规则未命中;若 Location 是 http,说明是应用层在跳
# 2) 绕开 DNS 与 CDN,直连源站 80 端口,判断“谁”在跳
curl -I -H 'Host: example.com' http://127.0.0.1
# 3) 展开全部生效配置(含 include),列出所有监听 80 的 server 块
# -T 需 nginx 1.9.2+;旧版本用 nginx -t -c /etc/nginx/nginx.conf 逐文件看
nginx -T | grep -n 'listen 80'
问:为什么有的域名跳、有的域名不跳?
因为 nginx 的虚拟主机匹配是“listen + server_name”两级匹配。请求没命中任何 server_name(比如直接用 IP 访问、或用未配置的子域名访问)时,会落到该端口上第一个 server 块,或标了 default_server 的那个。如果你的 80 端口只有 443 站点的“影子块”,或压根没有兜底块,就永远不会发生 nginx 强制 https 跳转。补一个显式兜底块最稳妥(default_server 参数自 nginx 0.7.44 起可用):
server {
listen 80 default_server; # 兜底:所有未匹配 server_name 的请求都进这里
server_name _;
return 301 https://$host$request_uri; # $host 取 Host 头,缺失时回退 server_name
}
问:80 端口能不能干脆关掉?
不能直接关。据 Let’s Encrypt 文档,ACME 的 HTTP-01 挑战默认通过 80 端口的 /.well-known/acme-challenge/ 路径完成,续期时同样依赖它;关掉 80 就必须改用 DNS-01 验证,或让跳转规则对该路径放行。这也是很多“续期突然失败”的隐藏原因。
问:跳转链越跳越多、甚至循环,怎么快速定位?
常见现象是 curl 报 curl: (47) Maximum (50) redirects followed,浏览器显示 ERR_TOO_MANY_REDIRECTS。此时往往不止 nginx 一处在跳:WordPress 的 siteurl/home 选项、Spring Boot 的 server.forward-headers-strategy=native(默认 none,2.x 起可设 framework/native)、宝塔面板的“强制 HTTPS”开关都会各自下发一次 301。先用 curl -IL 逐跳打印 Location,再 grep -rn "https" /path/to/app/config 找应用侧强制项。
问:套了 CDN 之后为什么反而跳不动了?
因为 TLS 已在 CDN 边缘终止,回源走的是明文 HTTP,源站 nginx 里 $scheme 恒为 http。此时再无条件 return 301,源站会把 CDN 的回源请求也跳回 https,形成回源循环。判据是看 $http_x_forwarded_proto:有该头且值为 https 就不跳。Cloudflare 侧应把 SSL/TLS 模式设为 Full (strict),否则源站证书不被校验,仍可能被降级回源。
# 仅在“客户端到边缘确实是 http”时才跳,避免回源循环
map $http_x_forwarded_proto $plain_http {
default 0;
"" 1; # 无该头 = 未经代理的直连明文请求
http 1;
https 0;
}
server {
listen 80;
server_name example.com;
if ($plain_http) {
return 301 https://$host$request_uri;
}
}
| 现象 | 最可能的根因 | 一条命令定位 |
|---|---|---|
curl -I 直接返回 200 |
80 端口 server 块没有 return/rewrite,或请求落到别的 server | nginx -T | grep -n 'listen 80' |
| 用 IP 访问不跳,用域名跳 | 缺少 default_server 兜底块 |
curl -I http://<服务器IP> |
| Location 已是 https 但仍循环 | 应用层或 CDN 再跳一次 | curl -IL http://example.com |
| CDN 开启后 502/522 或循环 | 源站无条件 301,回源协议为 http | curl -I -H 'Host: example.com' http://127.0.0.1 |
| 证书续期失败 | 80 端口被整段跳转,ACME 路径未放行 | curl -I http://example.com/.well-known/acme-challenge/test |
二、nginx 强制 https 跳转的完整实操步骤(以 nginx 1.24/1.26 为例)
下面按“先查环境、再配证书、写两个 server、测试热加载、留退路”的顺序走一遍。命令以 nginx 1.24.x / 1.26.x、systemd 发行版(Debian 12 / Ubuntu 22.04+)为准,其他发行版只需替换证书路径。
步骤 1:确认版本与模块。nginx 官方文档明确要求 SSL 功能依赖编译期模块,因此先验证再动手:
# 只看版本号
nginx -v
# 输出示例:nginx version: nginx/1.26.2
# -V 把详细信息打到 stderr,所以要 2>&1;有输出即说明 SSL 模块已编译进去
nginx -V 2>&1 | grep -o with-http_ssl_module
# 输出:with-http_ssl_module
# 改配置前先备份,文件名带日期便于回滚
cp /etc/nginx/nginx.conf{,.bak-$(date +%F)}
步骤 2:准备证书。据 Let’s Encrypt 文档,certbot 2.x 推荐用 webroot 或 nginx 插件签发,证书 90 天有效、自动续期免费:
# certbot 2.x;--webroot 要求 80 端口能访问 /var/www/html
certbot certonly --webroot -w /var/www/html
-d example.com -d www.example.com
--deploy-hook "systemctl reload nginx"
# 证书链:/etc/letsencrypt/live/example.com/fullchain.pem
# 私钥: /etc/letsencrypt/live/example.com/privkey.pem(archive 内实际文件默认 600)
成本参考:Let’s Encrypt 免费;商业 DV 证书常见 ¥0–300/年,OV 证书约 ¥800–3000/年。注意 live/ 下是软链,renew 后自动指向新文件,所以配置里写 live 路径即可,不要写死 archive 的时间戳目录。
步骤 3:写 80 端口的跳转 server。关键在两个变量:$host 取请求头 Host 并去掉端口,$request_uri 保留路径和查询串——用 $http_host 会把 :80 带进跳转地址,用 https://example.com$uri 则会丢掉 ?a=1 参数:
server {
listen 80 default_server;
listen [::]:80 default_server; # IPv6 也要监听,否则 AAAA 记录的用户不会被跳转
server_name example.com www.example.com;
# $host 不含端口;$request_uri 含路径 + 查询串,避免跳转后丢参数
return 301 https://$host$request_uri;
}
步骤 4:写 443 的 server。这里有一个版本坑,1.25.1 起 listen ... http2 参数被标记为 deprecated,改用独立的 http2 指令:
| 项目 | nginx 1.24.x | nginx 1.26.x |
|---|---|---|
| 开启 HTTP/2 写法 | listen 443 ssl http2; |
listen 443 ssl; + http2 on; |
listen 的 http2 参数 |
正常可用 | 可用但已 deprecated(1.25.1 起告警) |
ssl_protocols 默认值 |
TLSv1.2 TLSv1.3(1.23.4 起移除 TLSv1/1.1 默认支持) |
|
server {
listen 443 ssl;
http2 on; # nginx ≥ 1.25.1 用这一行
# listen 443 ssl http2; # nginx 1.24.x 及更早用这一行,二者不要同时写
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 显式写出,避免老配置文件残留 TLSv1 / TLSv1.1
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m; # 默认 off,开启后握手开销明显下降
ssl_session_timeout 1d;
root /var/www/html;
location / { try_files $uri $uri/ =404; }
}
步骤 5:测试与热加载。期望看到两行关键字,缺一不可:
nginx -t
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
systemctl reload nginx # 或 nginx -s reload
用 reload 而不是 restart:reload 会先启动新 worker 再优雅退出旧 worker,不断开现有连接;restart 会中断正在传输的请求。
步骤 6:灰度验证与回滚。301 会被浏览器长期缓存(Chrome 会缓存到磁盘),改错后用户端很难回滚。稳妥做法是先把 return 301 临时改成 return 302,跑 24 小时,确认没有混合内容告警、没有跳转循环、查询串未丢失后再换回 301:
# 验证跳转状态码与 Location,注意查询串是否保留
curl -I "http://example.com/a?b=1"
# HTTP/1.1 301 Moved Permanently
# Location: https://example.com/a?b=1
# 出问题时的回滚序列
cp /etc/nginx/nginx.conf.bak-2025-01-01 /etc/nginx/nginx.conf
&& nginx -t && nginx -s reload
顺带说明状态码选型:301 是永久重定向(RFC 7231 §6.4.2),语义上适合“以后都走 HTTPS”,但会被缓存;308 同为永久重定向(RFC 7538),区别是强制客户端保持原请求方法——POST 表单跳转不会被改成 GET。如果你的站点有大量 POST 提交,用 return 308 更安全;纯展示型站点用 301 即可,对搜索引擎更友好。
三、可复制的 nginx 强制 https 跳转配置与命令示例(含参数默认值)
配置能跑起来不难,难的是“跑对了”。下面每个片段都给出完整可复制的版本、参数默认值,以及验证命令——照着粘贴后能立刻判断是否生效。
Q1:最小可用的 80 端口跳转块长什么样?
# 放置位置:nginx.conf 的 http { } 块内,或 conf.d/default.conf
# 适用:nginx 1.10+(listen 与 return 语法在各主流版本一致)
server {
listen 80 default_server; # default_server 表示未匹配到 server_name 时的兜底
listen [::]:80 default_server; # IPv6 兜底,缺这行会让 AAAA 解析的客户端拿到 404
server_name example.com www.example.com;
access_log /var/log/nginx/http_redirect.log; # 独立日志,便于统计 301 命中量
return 301 https://$host$request_uri; # $host 优先取请求行/ Host 头,$request_uri 保留完整路径与查询串
}
最常见的“配了不生效”原因不是语法,而是被更靠前的 default_server 抢占:nginx 按配置文件加载顺序匹配,第一个声明 default_server 的 server 获胜,重复声明会直接报错 nginx: [emerg] a duplicate default server for 0.0.0.0:80。用 nginx -T | grep -n "default_server" 一次看清全部冲突点,再用 curl -sSI http://example.com/any/path | head -3 验证输出是否为 HTTP/1.1 301 Moved Permanently 且 Location 保留了原路径。
Q2:443 server 里该加哪些会话与 OCSP 参数?默认值是多少?
server {
listen 443 ssl;
http2 on; # nginx 1.25.1+ 新语法;更早版本用 listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_session_cache shared:SSL:10m; # 默认 none;10m ≈ 40000 个会话(nginx 文档:1MB 约 4000 个)
ssl_session_timeout 1d; # 默认 5m,过短会显著拉高完整握手比例
ssl_session_tickets on; # 默认 on(1.5.9+),多机部署时注意 ticket key 轮转
ssl_stapling on; # 默认 off,自 1.3.7 起支持
ssl_stapling_verify on; # 默认 off,需配合 ssl_trusted_certificate 校验链
ssl_trusted_certificate /etc/nginx/ssl/chain.pem;
resolver 1.1.1.1 8.8.8.8 valid=300s; # 必须有 resolver,否则 stapling 静默失败
}
注意 ssl_stapling 只在证书带 OCSP 地址时才有意义;Let’s Encrypt 已于 2025 年停止在证书中写入 OCSP URL(据 Let’s Encrypt 官方公告),此时 stapling 不会报错但也不产生效果。验证方式:openssl s_client -connect example.com:443 -status | grep -i "OCSP Response Status",出现 successful 才算真正生效。
Q3:老教程里的 rewrite 写法还能用吗?
能用,但据 nginx 官方文档(ngx_http_rewrite_module)明确建议:能用 return 时优先用 return。rewrite ^ https://$host$request_uri permanent; 里的 permanent 等价于 301,但它每次请求都要走一次 PCRE 正则匹配,高 QPS 下是白白的 CPU 开销。
| 维度 | return 301 | rewrite … permanent |
|---|---|---|
| 可用上下文 | server、location、if | server、location、if |
| 是否走正则引擎 | 否,直接构造响应 | 是,需匹配 pattern |
| 状态码 | 301(也可 308) | permanent = 301;redirect = 302 |
| 相对性能 | 更高 | 略低,取决于正则复杂度 |
| 官方建议 | 优先 | 仅在需要条件/正则捕获时 |
Q4:www 与根域怎么只跳一次?
把归一逻辑放进 443 的 server 块,而不是让 80 先跳 www 再跳根域,否则浏览器会收到两次 301,移动端首屏多出约一个 RTT:
server {
listen 443 ssl;
server_name example.com www.example.com;
# if 放在 server 级且只做 return,是 nginx 社区公认可接受的用法(不涉及 try_files 等指令的配置继承陷阱)
if ($host = www.example.com) {
return 301 https://example.com$request_uri;
}
}
Q5:前面挂了 SLB / CDN,怎么判断原始协议?
# http 块内定义映射:默认沿用 $scheme,只有头明确为 https 时才认为已加密
map $http_x_forwarded_proto $forwarded_scheme {
default $scheme;
https https;
}
server {
listen 80;
server_name example.com;
# 仅当请求来自可信 LB / CDN 回源网段时启用,否则攻击者可伪造 X-Forwarded-Proto: https 绕过跳转
if ($forwarded_scheme != https) {
return 301 https://$host$request_uri;
}
}
更稳妥的做法是用 set_real_ip_from + real_ip_header 锁定可信来源,或干脆让 CDN 侧配置“强制 HTTPS”回源规则,源站只监听 443。
Q6:HSTS 头怎么加才不把自己锁死?
# add_header 的 always 参数自 nginx 1.7.5 起支持,保证 4xx/5xx 响应也带该头
# 注意:location 内一旦出现 add_header,会覆盖 server 级的全部 add_header,需重复声明
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains' always;
# 灰度期先用:max-age=300;(5 分钟,出问题 5 分钟内可回滚)
HSTS 一旦下发 max-age=31536000 且 includeSubDomains,浏览器会在一年内拒绝该域及所有子域的 HTTP 访问;preload 还需向 hstspreload.org 提交并被 Chrome/Firefox 内置列表收录,移除周期以月计。因此顺序应是:300 秒 → 一天 → 一年,每一步都确认所有子域证书有效。
四、return 301、rewrite、308 与 HSTS:nginx 强制 https 跳转方案选型表
nginx 强制 https 跳转该用 return 301、rewrite permanent 还是 308?先看选型表,再决定写在哪一层。
| 方案 | 配置位置 | 状态码 | 浏览器缓存 | 典型场景 | 代价/注意点 |
|---|---|---|---|---|---|
return 301 |
server / location 级直接返回 | 301 | 强缓存 | 整站 http→https | 改错后必须清浏览器缓存 |
rewrite ... permanent |
server / location 级 | 301 | 强缓存 | 需要按正则或路径规则跳转 | 多一次 PCRE 匹配,易产生二次跳转 |
return 308 |
server / location 级 | 308 | 缓存 | API、表单 POST | 旧客户端兼容性需实测 |
| HSTS 响应头 | add_header |
无状态码 | 浏览器强制 https | 已全站 https 后加固 | 首次 http 访问仍需 301 |
| CDN Always Use HTTPS | 边缘规则 | 301 / 308 | 边缘缓存 | 已接入 CDN 的站点 | 源站仍须保留 80 兜底 |
301 和 302 差在哪,为什么调试期别用 301?据 RFC 9110 §15.4.2,301 表示资源永久迁移,Chrome、Firefox 会把它写入持久缓存且没有过期时间——线上把 return 301 https://example.com 的域名写错,用户会一直跳到错误地址,只能手动清缓存。调试期先用 return 302,确认无误再换 301。SEO 上 301 用于把 http 与 https 两套 URL 的权重合并到同一地址,这也是 Let’s Encrypt 的 certbot --redirect 默认插入 301 而非 302 的原因。
308 什么时候才必须用?308 由 RFC 7538 定义、现并入 RFC 9110 §15.4.9,与 301 的唯一区别是强制保留请求方法与 body。API 网关把 http://api.example.com 跳到 https:// 时必须用 308,否则 POST 会被降级为 GET、请求体丢失。普通网页只有 GET/HEAD,用 301 即可,不必为”新”盲目上 308。
# 整站 http→https:server 级 return 自 nginx 0.8.42 起可用;308 需 nginx ≥ 1.13.0
server {
listen 80;
server_name example.com www.example.com;
# 非幂等方法(POST/PUT)用 308,保留方法与请求体
if ($request_method !~ ^(GET|HEAD)$) {
return 308 https://$host$request_uri;
}
# 普通页面用 301;$request_uri 保留原始路径与查询串
return 301 https://$host$request_uri;
}
return 和 rewrite 到底选哪个?return 在 server/location 上下文直接结束请求,不经过正则;rewrite ... permanent 要先做 PCRE 匹配再返回 301,与 last/break 组合时还可能产生二次跳转。1 万 QPS 的静态站上两者性能差异可以忽略,但排错时 return 的跳转链更短。
# 只有"按路径规则跳转"才需要 rewrite;permanent 即返回 301
server {
listen 80;
server_name example.com;
# 旧目录永久迁移到 https 新路径
rewrite ^/old/(.*)$ https://example.com/new/$1 permanent;
# 兜底:其余路径整站跳转
return 301 https://$host$request_uri;
}
HSTS 能代替跳转吗?不能。据 RFC 6797,Strict-Transport-Security 只在浏览器收到过一次 HTTPS 响应后才生效,首次 http:// 访问仍然依赖 nginx 强制 https 跳转兜底。max-age 单位是秒,31536000 等于 1 年;上线初期建议先用 max-age=300 验证,再加 includeSubDomains,最后才考虑 preload(提交后极难撤回)。
# 必须写在 HTTPS 的 server 块内;add_header 的 always 参数需 nginx ≥ 1.7.5
server {
listen 443 ssl;
server_name example.com;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
用了 CDN 怎么避免双跳?Cloudflare 的 Always Use HTTPS 在边缘直接返回 301/308,请求根本到不了源站;但若源站无条件跳转,绕过 CDN 的直连 IP、健康检查就会拿到 301 而非内容。正确做法是源站按 X-Forwarded-Proto 判断,同时保留 80 端口兜底跳转,不要只依赖 CDN。
- SSL证书申请 · SSL证书购买 · SSL证书安装配置
- HTTPS证书申请 · SSL证书安装部署 · 证书续费
- 代购 SSL 证书 · DigiCert / GeoTrust / RapidSSL 单域名与通配符
# map 需放在 http 块中
map $http_x_forwarded_proto $force_https {
default 1; # 直连 80:兜底跳转
https 0; # CDN 回源且原始协议为 https:不再跳转,避免双跳
}
server {
listen 80;
server_name example.com;
if ($force_https) {
return 301 https://$host$request_uri;
}
# …此处为源站正常内容或反向代理配置
}
验证:
curl -I http://example.com应返回HTTP/1.1 301 Moved Permanently与Location: https://example.com/;若看到302,或 443 端口返回497(nginx 在 SSL 端口收到明文 HTTP 时的内部错误码),说明跳转块位置或 listen 指令写错了。
五、nginx 强制 https 跳转常见错误与真实报错排查
为什么配置看起来没问题,浏览器却一直转圈或直接报错?因为 nginx 强制 https 跳转失败时,报错信息往往出现在三个不同层面:浏览器、nginx 启动日志、后端应用。排查顺序应该是「先看跳转链,再看端口,最后看配置加载」,而不是直接去改 server 块。
第一步永远是抓取跳转链。据 nginx 官方文档,curl -L 的跟随上限由 --max-redirs 控制(默认 50),把它压到 3 就能快速暴露循环:
curl -I -L --max-redirs 3 http://example.com
# -I 只取响应头;-L 跟随 3xx;--max-redirs 3 限制跳数
# 若输出连续出现两条 Location: https://example.com/ → 说明 443 的 server 块里又写了 return 301 https://...
# 超出上限时 curl 返回:curl: (47) Maximum (3) redirects followed
ERR_TOO_MANY_REDIRECTS(重定向次数过多)最常见于两种互跳:一是 443 的 server 块里误留了 return 301 https://$host$request_uri;,自己跳自己;二是 WordPress 等应用层仍把站点地址写死为 http——nginx 跳到 https,应用再 301 回 http。用 SQL 或 WP-CLI 确认,而不是猜:
wp option get home --allow-root # 应输出 https://example.com
wp option get siteurl --allow-root # 同上;两者不一致也会触发跳转
# 修正:wp option update home 'https://example.com' && wp option update siteurl 'https://example.com'
400 Bad Request / The plain HTTP request was sent to HTTPS port:用 http:// 打了 443 端口,或 listen 443 ssl; 的 ssl 参数写错。这条 400 由 nginx 的 SSL 模块直接返回,不经过 location:
curl -v http://example.com:443
# 关键行:Connected to example.com (...) port 443
# 随后返回 HTTP/1.1 400 Bad Request 与 "The plain HTTP request was sent to HTTPS port"
# 正确写法应为 https://example.com,并确认 listen 443 ssl; 中 ssl 未被遗漏
启动期的两类报错与配置重复有关,用下面三条命令即可定位:
nginx -t # 语法与重复项自检
grep -rn 'default_server' /etc/nginx/ # 找到多个 0.0.0.0:80 的 default_server
nginx -T | grep -n 'server_name' # -T 打印合并后的完整配置,定位同名 server_name
| 报错 / 现象 | 典型根因 | 定位命令 |
|---|---|---|
| ERR_TOO_MANY_REDIRECTS | 443 块内自跳,或应用层 WP_HOME 仍为 http | curl -I -L --max-redirs 3 |
| 400 plain HTTP request sent to HTTPS port | http:// 访问 443,或 listen 443 ssl 漏写 ssl |
curl -v http://host:443 |
| [emerg] duplicate listen options | 同一端口出现两个 default_server | grep -rn default_server /etc/nginx/ |
| [warn] conflicting server name … ignored | 多个 server 块写同一 server_name | nginx -T | grep -n server_name |
| Mixed Content | 页面内仍硬编码 http:// 资源 | DevTools Console 定位 URL |
跳转成功了,但页面样式丢失并报 Mixed Content?据 Mozilla MDN,浏览器会拦截 HTTPS 页面中的 http:// 子资源。除了把资源改为 // 协议相对地址,还可在 443 块加一条 CSP,让浏览器自动把不安全请求升级:
add_header Content-Security-Policy "upgrade-insecure-requests" always;
# always 保证 4xx/5xx 响应也带上;CSP Level 1 起支持,Chrome/Firefox/Safari 均已实现
499 和 502 要不要改跳转?499 是 nginx 自定义状态码,表示客户端在响应前主动断开,跳转链过长会显著推高它,先缩短链路再谈调参;502 则指向 upstream,据 ngx_http_proxy_module 文档 proxy_read_timeout 默认 60s,后端慢时可放宽并配置重试:
proxy_read_timeout 120s; # 默认 60s
proxy_next_upstream error timeout http_502; # 默认 error timeout
proxy_next_upstream_tries 2; # 默认 0,即不限制次数
另外别忘了 nginx -s reload 只对已成功加载的配置生效:若 nginx -t 失败,线上仍在跑旧配置,你看到的跳转行为就是上一版遗留的——这也是「改了没生效」最常见的原因。
六、如何验证 nginx 强制 https 跳转已生效:5 组命令与检查点
“我已经配好了 return 301,怎么确认它真的生效?”——别只看浏览器地址栏变绿,浏览器有缓存、CDN 有边缘节点、DNS 也可能把你指到别处。下面 5 组命令从“客户端视角”“跟随链路”“绕过 CDN”“TLS 握手”“服务端日志”五个层面交叉验证 nginx 强制 https 跳转,任何一层对不上,问题就定位到那一层。
| 组 | 命令核心 | 检查目的 | 期望结果 |
|---|---|---|---|
| 1 | curl -I |
跳转是否发出、Location 是否保留路径与查询串 | HTTP/1.1 301 + Location: https://… |
| 2 | curl -IL --max-redirs 3 |
跟随链路是否终止于 200,有无循环 | 最终 HTTP/2 200 |
| 3 | curl --resolve |
绕过 DNS/CDN,确认源站 nginx 独立生效 | 源站直接返回 301/308 |
| 4 | openssl s_client |
证书有效期、CN/SAN 是否覆盖域名 | notAfter 未过期 |
| 5 | awk '$9==301' |
服务端是否真的在回 301,来源是否异常 | 状态码列命中 301 |
第一组:确认跳转本身与 Location 拼接正确。-I 只发 HEAD、只取响应头,不下载正文,对带宽和 CDN 计费都友好。
# -s 静默进度条,-S 出错时仍打印错误,-I 只取响应头
curl -sSI http://example.com/path?a=1
# 期望首行: HTTP/1.1 301 Moved Permanently
# 期望响应头: Location: https://example.com/path?a=1
# 若 Location 丢了 /path 或 ?a=1,说明用了 return 301 https://$host; 而非 $request_uri
第二组:跟随跳转,检查链路是否收敛。--max-redirs 默认值为 50,设成 3 可以在出现“https 又跳 https”这类死循环时快速失败,而不是默默跟 50 次。
curl -sSIL --max-redirs 3 http://example.com
# 期望最后一个响应块为 HTTP/2 200
# 出现循环时报错: curl: (47) Maximum (3) redirects followed
curl: (47) Maximum (3) redirects followed是典型信号:多半是 CDN 回源协议写成 HTTP,或 nginx 的if ($scheme != "https")在代理层看到的是http,需要改用$http_x_forwarded_proto判断。
第三组:绕过 CDN 直连源站。--resolve 的格式是 host:port:addr,把域名强行解析到指定 IP,不改 /etc/hosts、不影响其他进程,是确认“源站 nginx 强制 https 跳转是否独立生效”最干净的办法。
# 把 example.com:80 钉到源站 127.0.0.1,Host 头与 SNI 仍是 example.com
curl -sSI --resolve example.com:80:127.0.0.1 http://example.com
# 若这里 200 而公网 301,说明跳转是 CDN 边缘做的,源站配置缺失
第四组:TLS 层不能只看“能打开”。据 OpenSSL 文档,-servername 用于发送 SNI,多站点/多证书部署时漏掉它,会拿到默认站点的证书而误判。
openssl s_client -connect example.com:443 -servername example.com -tls1_2 /dev/null
| openssl x509 -noout -dates -subject -ext subjectAltName
# 关注 notBefore/notAfter 是否覆盖当前时间,SAN 是否含 example.com 与 www
# 报 verify error:num=10:certificate has expired 即为证书过期
第五组:回到服务端看日志。默认 combined 格式下 $9 就是状态码、$1 是客户端 IP、$7 是请求 URI;如果你自定义过 log_format,字段序号会变,先核对 nginx.conf 再跑。
# 实时看 301,关注来源 IP 与路径是否有异常爬虫或监控被反复跳转
tail -f /var/log/nginx/access.log | awk '$9==301 {print $1, $7, $9}'
# 用 308 的场景把 301 换成 308(308 保留 POST 方法与请求体)
最后做一次端到端复核,一条命令同时拿到状态码与目标地址:
curl -sS -o /dev/null -w '%{http_code} %{redirect_url}n' http://example.com
# 期望输出: 301 https://example.com/
再用 Mozilla Observatory 与 SSL Labs 复核 HSTS(Strict-Transport-Security,建议 max-age=31536000 起,先别急着加 includeSubDomains 与 preload)、最低 TLS 版本(Mozilla 服务器端 TLS 配置指南推荐 TLS 1.2 起)与证书链完整性。据 Let’s Encrypt 文档,证书 90 天有效、到期前 30 天可续期,因此第四组的 notAfter 应当纳入日常巡检,而不是等跳转失效才排查。
七、多站点、反向代理与 CDN 下的 nginx 强制 https 跳转进阶
多个域名共用一个 80 端口 server 块,跳转为什么会串站?
nginx 在 80 端口按 Host 匹配 server_name,匹配不到就落到该端口的 default_server。把 a.com、b.com 全塞进同一个块并标成 default_server,等于主动放弃隔离:任意解析到你 IP 的域名都会被跳到主站。更常见的症状是配置重复时 nginx -t 直接拒绝启动,报 nginx: [emerg] a duplicate default server for 0.0.0.0:80 in /etc/nginx/conf.d/xxx.conf。正确做法是一个域名(含 www)一组 80/443 块,80 块只做跳转,443 块只做服务。
# /etc/nginx/conf.d/example.conf —— 适用于 nginx 1.18+,1.25.1 起可用 http2 on
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com; # 关键:只列本域名,不写 default_server
return 301 https://$host$request_uri; # 用 $host 保留实际访问的 www/裸域
}
server {
listen 443 ssl;
http2 on; # nginx < 1.25.1 请改用 listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# ... location 略
}
泛解析 *.example.com 必须配通配证书,否则 SNI 握手上就断:curl https://foo.example.com 会返回 SSL: no alternative certificate subject name matches target host name,浏览器侧表现为 ERR_CERT_COMMON_NAME_INVALID。另外通配符只覆盖一级子域,*.example.com 不含 example.com 本身,根域必须单独签。
nginx 在前、Tomcat 在后,为什么页面还是 http 链接?
因为 TLS 在 nginx 终止后,回源请求本身就是明文 HTTP,后端拿到的 request.getScheme() 永远是 http,拼接出的静态资源、重定向 Location 全是 http,浏览器随即报 Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http://...'。在 443 的 location 里补三个头即可(据 nginx 官方 proxy 模块文档,$scheme 取的是当前连接的协议):
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host; # 保留原始域名
proxy_set_header X-Forwarded-Proto $scheme; # 后端据此判断 https
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Port $server_port; # 非 443 端口时有用
}
# Tomcat 侧还需在 server.xml 的 Host 内启用:
# <Valve className="org.apache.catalina.valves.RemoteIpValve"
# remoteIpHeader="X-Forwarded-For"
# protocolHeader="X-Forwarded-Proto" />
ALB 或 Cloudflare 终结 TLS 后,源站该怎么判断协议?
此时源站看到的是 http,$scheme 已经不可信;直接用 $http_x_forwarded_proto 又会被客户端伪造——任何人都能手动加一个 X-Forwarded-Proto: https 头绕过跳转。要先用 geo 锁定 LB 网段,再用 map 组合判断:
# 只信任来自负载均衡网段的转发头(网段按你的 ALB/Cloudflare IP 段填写)
geo $trusted_proxy {
default 0;
10.0.0.0/16 1; # 例:AWS ALB 所在 VPC 网段
}
map "$trusted_proxy:$http_x_forwarded_proto" $forwarded_scheme {
default $scheme; # 不可信来源一律回落到真实连接协议
"1:https" https;
"1:http" http;
}
server {
listen 80;
server_name example.com www.example.com;
if ($forwarded_scheme = https) { return 301 https://$host$request_uri; }
return 301 https://$host$request_uri; # 兜底:80 一律跳转
}
Cloudflare 侧据其官方文档建议把 SSL/TLS 模式设为 Full (strict),源站 443 必须持有有效证书(自签会报 526);开启 Edge 的 “Always Use HTTPS” 后,源站 80 的跳转仍建议保留作兜底,避免有人绕过 CDN 直连 IP。各形态的判断依据对比如下:
| 部署形态 | 源站看到的协议 | 可信的判断变量 | 关键动作 |
|---|---|---|---|
| nginx 直接终结 TLS | https | $scheme |
listen 443 ssl,80 块 return 301 |
| nginx + Tomcat | http | nginx 侧 $scheme;后端读 X-Forwarded-Proto |
三件套 proxy_set_header + RemoteIpValve |
| ALB / Cloudflare 终结 | http | map + geo 后的 $forwarded_scheme |
锁定 LB 网段,拒绝伪造头 |
通配证书怎么续?
Let’s Encrypt 只支持 DNS-01 签发通配证书,必须先在 _acme-challenge.example.com 写入 TXT 记录:
certbot certonly --manual --preferred-challenges dns
-d '*.example.com' -d example.com # 通配符不含根域,根域要单独 -d
--server https://acme-v02.api.letsencrypt.org/directory
# 注意:--manual 不会自动续期,生产环境请改用
# certbot certonly --dns-cloudflare --dns-cloudflare-credentials /root/.secrets/cf.ini -d '*.example.com' -d example.com
怎么第一时间发现跳转失效或证书过期?
用 curl 的 -w 只取状态码做探针,期望值恒为 301:
curl -o /dev/null -s -w '%{http_code}n' http://example.com
# 输出 301 为正常;200 说明跳转规则被覆盖,000 多为连接失败
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null
| openssl x509 -noout -enddate # 证书剩余天数 < 14 天触发续签检查
把这两条挂到每分钟一次的探针上,状态码非 301 或证书剩余天数低于 14 天即告警,就能覆盖多站点、反代、CDN 三种拓扑下最常见的失效路径。
正式环境用 301,表示永久跳转,浏览器会缓存并把 http 权重合并到 https;调试期用 302,避免改错后浏览器一直记住旧跳转。若涉及 POST 表单或 API,考虑 308 以保留请求方法。
先用 curl -I -L –max-redirs 3 http://example.com 看 Location 链,重点查 443 server 内是否又写了 return 301 https://…、CDN 回源协议是否被改成 http、以及 WordPress 或 Spring Boot 是否也强制 https。三处只保留一处主跳转,其余做兜底。
据 Let's Encrypt 文档,HTTP-01 验证器会跟随 80 到 443 的重定向,因此全站 301 通常不影响续签;但建议为 /.well-known/acme-challenge/ 加 location 例外,避免 CDN 缓存或跳转规则误伤验证文件。
要配,二者不是二选一。Cloudflare 在边缘做 301 可以减少回源,但非 CDN 直连、内部监控和切换 CDN 时仍会访问源站 80;源站 nginx 保留 return 301 作为兜底,并用 X-Forwarded-Proto 判断避免回源循环。
常见原因是用了 http:// 访问 443 端口,或 listen 443 ssl 与 proxy_pass 混用。用 curl -v http://example.com:443 查看 Connected to … port 443,确认协议与端口匹配;同时检查 nginx -t 是否通过、是否有重复 default_server。
不需要重启,执行 nginx -t 确认 syntax is ok 与 test is successful 后,用 systemctl reload nginx 或 nginx -s reload 热加载即可。restart 会断开现有连接,生产环境优先 reload。
建议在确认全站 https、子域证书齐全后再开。先设 max-age=300 观察 1 到 2 天,再逐步升到 31536000;includeSubDomains 要确认所有子域都支持 https,preload 需向浏览器厂商提交且回滚困难。
本文由 sslgood.com 安全团队基于生产环境实战经验撰写,关键结论均经过技术复核。