跳到主要内容
安装配置教程

OpenResty 如何强制 HTTPS?从 301 跳转配置到排查验证的完整实操指南

openresty 强制https — OpenResty 如何强制 HTTPS?从 301 跳转配置到排查验证的完整实操指南
核心结论

在 OpenResty 中强制 HTTPS 的常用做法是在 80 端口 server 块中写 return 301 https://$host$request_uri;,配合 listen 80 default_server 与 server_name 匹配,单次跳转通常在 5 ms 内完成。 优先用 return 301 而不是 rewrite ^ https://$host$request_uri permanent,因为 return 在 rewrite 阶段前执行,可少一次正则匹配;OpenResty 1.21.4.1 与 1.25.3.1 均支持。 HSTS 通过 add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains' always; 在 443 server 下发,首次上线建议先用 max-age=300 观察 24 小时。 验证用 curl -I http://example.com/foo?bar=1 看 301 与 Location,用 openssl s_client -connect example.com:443 -servername example.com -tls1_2 看证书链与 TLS 版本。

为什么 http:// 还能打开?OpenResty 强制 HTTPS 的背景与根本原因

因为 OpenResty 安装包自带的 conf/nginx.conf 默认只监听 80 端口,既没有 443 server,也没有任何跳转规则。用官方 1.21.4.1 / 1.25.3.1 的预编译包安装后,先确认一下现状:

# 查看默认配置里所有 listen 指令(两个版本安装包内容一致)
grep -n "listen|return 30" /usr/local/openresty/nginx/conf/nginx.conf
# 典型输出只有一行,且没有 443、没有 return 301:
#   38:        listen       80;

# 验证当前 80 端口确实返回 200 而不是重定向
curl -sI http://example.com/ | head -n 3
# HTTP/1.1 200 OK          <-- 明文 200,浏览器就会照常渲染
# Server: openresty/1.25.3.1

用户只输入 example.com 时,浏览器默认补全 http://,服务器回 200 就以明文加载整页。所谓 openresty 强制https,本质是让 80 端口的 server 返回 301/308,把同一 $host 与 $request_uri 指向 https://。选哪个状态码有实际差异:

状态码 语义 是否保留请求方法 浏览器缓存 来源
301 永久重定向 历史实现常改成 GET 可长期缓存,改回难 RFC 7231 §6.4.2
302 临时重定向 常改成 GET 不缓存 RFC 7231 §6.4.3
307 临时重定向 严格保留 不缓存 RFC 7231 §6.4.7
308 永久重定向 严格保留 可长期缓存 RFC 7538

跳转写法本身只有几行,坑几乎都在 $scheme 上。OpenResty 文档明确 $scheme 只有 http 和 https 两个值;当 TLS 在 SLB / CDN 上终止、回源走 HTTP 时,源站看到的永远是 http,此时按 $scheme 判断会把自己也重定向到 https,形成死循环,浏览器报 ERR_TOO_MANY_REDIRECTS。正确做法是优先信任代理头:

# http 块内定义映射:直连用 $scheme,回源时读代理头
map $http_x_forwarded_proto $client_scheme {
    default $scheme;   # 无代理头(直连)时退回真实协议
    https   https;     # SLB / Nginx 反代
    http    http;
}
# Cloudflare 用的是 CF-Visitor: {"scheme":"https"},需单独判断
map $http_cf_visitor $cf_scheme {
    default          "";
    "~*"scheme":"https""  https;
}

server {
    listen 80;
    server_name example.com;
    # 已是 https 就不再跳,避免循环;$request_uri 保留原始路径与查询串
    if ($client_scheme = http) {
        return 301 https://$host$request_uri;
    }
    if ($cf_scheme = https) {
        return 301 https://$host$request_uri;
    }
}

另一个常见误区是 HSTS。据 MDN 与 RFC 6797,Strict-Transport-Security 只能由 HTTPS 响应下发,浏览器会直接忽略 80 端口上的同名头;而且 add_header 默认只对 200/204/301/302/304 生效,写在 location 里遇到 4xx/5xx 就丢失,必须加 always:

server {
    listen 443 ssl;
    http2 on;                      # 1.25.x 起推荐写法,1.21.x 用 listen 443 ssl http2;
    server_name example.com;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

页面主文档跳到 HTTPS 后,地址栏仍可能不显示锁标志,原因是混合内容:img src、fetch()、后端返回的绝对 URL 里还写着 http://。除了改后端 baseURL,可以在 443 server 里下发 CSP 兜底:add_header Content-Security-Policy "upgrade-insecure-requests" always;。

上线窗口也要挑。据 Let’s Encrypt 文档,证书有效期为 90 天、官方建议每 60 天续期一次;如果证书只剩不到 30 天且自动续期尚未验证通过,此时开启 openresty 强制https,一旦续期失败就是全站不可用,而不只是 80 端口。切换前先用 openssl x509 -in fullchain.pem -noout -enddate 确认剩余天数。

OpenResty 强制 HTTPS 的完整实操步骤(6 步)

这 6 步是顺序依赖的:版本决定 http2 怎么写,备份决定出错时能不能 30 秒回滚,证书和 443 server 必须先就绪,否则 80 端口一跳过去就是 502/连接被拒。

  1. 备份与版本确认。先看清 built with OpenSSL 那一行——它决定了 ssl_protocols 能写到哪个版本(OpenSSL 3.0.13 支持 TLSv1.3,若链接的是 1.1.1 则同样支持,但 OpenSSL 1.0.2 系列只有 TLSv1.2 上限)。
# 1) 版本与 TLS 库,head -3 足够看到关键两行
openresty -V 2>&1 | head -3
# nginx version: openresty/1.25.3.1
# built with OpenSSL 3.0.13 30 Jan 2024
# TLS SNI support enabled

# 2) 备份 conf 目录,按分钟打时间戳,只保留 7 天
mkdir -p /data/backup
tar -czf /data/backup/nginx-$(date +%F-%H%M).tar.gz /usr/local/openresty/nginx/conf
find /data/backup -name 'nginx-*.tar.gz' -mtime +7 -delete

第 2 步:准备证书。Let’s Encrypt 官方文档推荐 ACME 客户端用 certbot 或 acme.sh,两者都能签发含 www 的多域名证书,差异如下:

对比项 acme.sh 3.0.7 certbot 2.11
运行时依赖 纯 shell,无 Python 需 Python 3.9+
默认 CA ZeroSSL,需显式切 Let’s Encrypt Let’s Encrypt
证书落地路径 --fullchain-file/--key-file 直接写到指定路径 /etc/letsencrypt/live/<域名>/ 符号链接
续期后动作 --reloadcmd 持久化到账户配置 --deploy-hook 或 renewal-hooks/deploy/
# acme.sh 3.0.7:切默认 CA 为 Let's Encrypt,用 webroot 验证(80 端口需可达)
acme.sh --set-default-ca --server letsencrypt
acme.sh --issue -d example.com -d www.example.com --webroot /usr/local/openresty/nginx/html

# 安装到统一目录,并注册续期后的 reload 钩子
acme.sh --install-cert -d example.com 
  --key-file       /etc/nginx/ssl/privkey.pem 
  --fullchain-file /etc/nginx/ssl/fullchain.pem 
  --reloadcmd      "systemctl reload openresty"

# 私钥必须 600,且属主为 worker 运行用户(默认 nobody,按实际改)
chown -R nginx:nginx /etc/nginx/ssl/ && chmod 600 /etc/nginx/ssl/privkey.pem

第 3 步:配置 443 server。OpenResty 1.25.3.1 基于 nginx 1.25.3,已支持独立的 http2 on;(nginx 1.25.1 引入);更早的 1.21.4.1 只能写 listen 443 ssl http2;,混用会直接 [emerg] unknown directive "http2"。

server {
    listen 443 ssl;
    http2 on;                              # 旧版改回 listen 443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate     /etc/nginx/ssl/fullchain.pem;   # 必须全链,缺中间证书 Android 报错
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;   # OpenSSL 3.0.x 默认即此,写出来是防误改
    ssl_session_cache   shared:SSL:10m;    # 默认 none,多 worker 共享可省一次握手
    ssl_session_timeout 1d;

    location / { proxy_pass http://127.0.0.1:8080; }
}

第 4 步:80 端口跳转。301 是永久重定向(RFC 7231 §6.4.2),浏览器会缓存;调试期想避免缓存可临时改 302 或 308(RFC 7538,保留 POST 方法)。

server {
    listen 80 default_server;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
    # $host 取请求 Host 且不含端口、无 Host 时回落到 server_name
    # $request_uri 保留完整 /path?query,不会丢参数
}

第 5 步:多域名与 SLB 回源。若前面挂了 SLB/ALB 做 HTTPS 卸载,源站收到的永远是 80 明文,靠 $http_x_forwarded_proto 判断,否则会跳转死循环。

http {
    map $http_x_forwarded_proto $forwarded_scheme {
        default $scheme;   # 无该头时按真实协议
        https   https;
    }
    server {
        listen 80;
        server_name example.com;
        if ($forwarded_scheme != https) {
            return 301 https://$host$request_uri;
        }
    }
}

第 6 步:测试与 reload。-t 只校验配置语法和证书可读性,不做热加载;reload 才是平滑切换(旧 worker 处理完存量连接后退出)。

openresty -t
# nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test is successful

systemctl reload openresty        # 或 /usr/local/openresty/bin/openresty -s reload

# 验证跳转是否带全 path 与 query
curl -sI http://example.com/path?q=1 | grep -i '^location'
# location: https://example.com/path?q=1

失败时先回滚再查日志,不要在线改:

tar -xzf /data/backup/nginx-2025-01-01-1200.tar.gz -C /
openresty -t && tail -n 20 /usr/local/openresty/nginx/logs/error.log
nginx: [emerg] cannot load certificate "/etc/nginx/ssl/fullchain.pem": BIO_new_file() failed (SSL: error:8000000D:system library::Permission denied)
nginx: [emerg] unknown directive "http2" in /usr/local/openresty/nginx/conf/nginx.conf:42

第一条是 worker 用户读不到私钥(属主或 600 权限错),第二条是版本与指令不匹配——都能从 [emerg] 行直接定位到文件行号。加密套件若需更严格的兼容矩阵,可参照 Mozilla SSL Configuration Generator 的 intermediate 档位补 ssl_ciphers 与 ssl_prefer_server_ciphers。

关键配置与命令示例:80 跳 443、HSTS 与代理头的最小片段

先把结论说在前面:在 OpenResty 里做 HTTPS 强制跳转,本质上就是两个 server 块——一个守在 80 端口只做 return 301,一个守在 443 端口负责真正的 TLS 终结。两者都写在 http {} 块内,不要塞进 location。

80 端口最小片段(放在 http 块内):

# /usr/local/openresty/nginx/conf/nginx.conf  →  http { } 内
server {
    listen 80 default_server;              # 整个配置里 default_server 只能出现一次
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;  # $request_uri 自带查询串,?bar=1 不会丢
}

注意 $host 取的是请求头 Host(已小写、已去端口),比 $server_name 更安全——后者在匹配失败时会退化成 default_server 的名字,导致跳转到错误域名。若你在多个 server 块里重复写 default_server,openresty -t 会直接报错:

nginx: [emerg] a duplicate default server for 0.0.0.0:80 in /usr/local/openresty/nginx/conf/nginx.conf:43

443 端口最小片段:

server {
    listen 443 ssl;
    http2 on;                              # OpenResty ≥ 1.21.4.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_protocols       TLSv1.2 TLSv1.3;   # 据 Mozilla SSL Configuration Generator,现代配置应只保留这两个
    add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains' always;
}

always 参数不可省——否则 4xx/5xx 响应不会带 HSTS 头,而错误页恰恰是攻击者最想降级的入口。

HSTS 别一步到位,按灰度推进:

阶段 max-age 观察期 回滚成本
灰度 300 24 小时 5 分钟内可撤回
稳定 31536000 — 需等浏览器缓存过期
preload 31536000 + includeSubDomains + preload 提交 hstspreload.org 后数周 数月,且子域必须全部有证书

据 Let’s Encrypt 文档提示,includeSubDomains 会连带约束 mail.、api. 等子域;任一子域没有有效证书,用户就会看到无法点击「继续访问」的硬错误。

反代到上游时的四个头,缺一不可:

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host              $host;
    proxy_set_header X-Real-IP         $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;               # 上游据此判断原始协议
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
}

Spring Boot 2.2+ 还需在 application.properties 打开 server.forward-headers-strategy=framework(默认 NONE),否则 request.getScheme() 仍返回 http,重定向会打回 80 端口造成死循环。

改完必须验证的四条命令:

openresty -t                                   # 语法检查,先过这一关再 reload
curl -I 'http://example.com/foo?bar=1'         # 期望:301 + Location: https://example.com/foo?bar=1
curl -I https://example.com                    # 期望:200 且响应头含 strict-transport-security
openssl s_client -connect example.com:443 -servername example.com -tls1_2 </dev/null
# OpenSSL 3.0.x 输出中应看到:Protocol : TLSv1.2 / Verify return code: 0 (ok)

-servername 不能省,否则 SNI 缺失会拿到默认证书而非该域名证书,验证结果失真。

最后加一行日志格式,让跳转可观测:

log_format main '$remote_addr $scheme $host $request_uri $status $http_x_forwarded_proto';

reload 之后 tail -f /usr/local/openresty/nginx/logs/access.log | grep ' 301 ',能直接看到哪些 URL 还在走 HTTP。这也是排查 openresty 强制 https 是否真正覆盖全站最快的手段——如果灰度期间这行日志持续增长,说明还有页面在写死 http:// 链接,先修代码再调大 max-age。

return 301、rewrite permanent 与 308 怎么选?参数对比与方案选型表

做 openresty 强制https 时,最常见的犹豫是:return 301、rewrite ... permanent、return 308 三者都能跳,到底写哪个?它们的状态码语义、执行阶段和客户端兼容性差别很大,先看选型表再动手。

方案 指令示例 状态码 执行阶段 / 开销 适用场景
return 301 return 301 https://$host$request_uri; 301 rewrite 阶段直接返回,不经过 PCRE 正则匹配 普通网站、SEO 永久跳转(默认首选)
rewrite permanent rewrite ^ https://$host$request_uri permanent; 301 rewrite 阶段,需编译并匹配正则 需要按路径规则改写后再跳转
return 308 return 308 https://$host$request_uri; 308 同 return,但保留请求方法与 body API、POST 表单提交
error_page 497 error_page 497 =301 https://$host$request_uri; 301 错误处理阶段触发 兜底:明文 HTTP 误打到 443 端口
Lua 跳转 ngx.redirect(url, 301) 301 Lua 阶段,需 lua 模块 动态域名、AB 测试、灰度分流

为什么 return 301 通常是最优解?据 Nginx 官方文档对 ngx_http_rewrite_module 的说明,return 在 rewrite 阶段直接结束请求并返回响应,不启动 PCRE 引擎;而 rewrite 需要先编译正则再逐条匹配,高 QPS 下这条差异会被放大。OpenResty 1.25.3.1(基于 Nginx 1.25.3)的 return 支持 301/302/303/307/308,默认不带状态码时返回 302。

server {
    listen 80;
    server_name example.com www.example.com;

    # 推荐写法:无正则、无变量捕获,rewrite 阶段直接 301
    return 301 https://$host$request_uri;
}

# 需要按路径分别跳转时才用 rewrite,permanent 关键字等价于 301
server {
    listen 80;
    server_name legacy.example.com;

    rewrite ^/old/(.*)$ https://$host/new/$1 permanent;
    rewrite ^          https://$host$request_uri permanent;
}

rewrite 在 location 里踩坑最多。permanent 会立即返回 301,其后的 proxy_pass 永远不执行——这也是很多“openresty 强制https 配好后接口 404”的真实原因。需要代理时把跳转放到 server 级,或在 location 内改用 return。

308 该不该用?308 由 RFC 7538 定义,明确要求客户端保留原请求方法和 body,而 301 在 RFC 7231 中允许客户端把 POST 改成 GET(多数浏览器确实会改)。因此纯 API 网关建议 308。但 Nginx/OpenResty 自 1.13.0 才支持 return 308,且 IE11 等老客户端对 308 支持有限,面向公众的站点仍以 301 为主。另需注意:return 308 不会读 body,大文件上传场景靠它跳转会丢失数据,应在客户端直接改用 HTTPS 端点。

# 兜底:明文 HTTP 请求打到了 443 端口时,Nginx 抛出内部错误码 497
server {
    listen 443 ssl;
    server_name example.com;

    error_page 497 =301 https://$host$request_uri;
}

HSTS 不能替代跳转。据 Mozilla 的 Strict-Transport-Security 文档,HSTS 只在浏览器已经通过 HTTPS 收到过该响应头之后才生效,用户首次访问仍会先发一个明文 HTTP 请求,80 端口上的跳转必须保留。Mozilla SSL Configuration Generator 的现代配置默认给出 max-age=63072000(2 年)。若源站位于 Cloudflare 之后并开启了 Always Use HTTPS,CDN 已做跳转、源站再 301 就形成双跳,应改为依据回源头判断:

server {
    listen 443 ssl;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;

    # CDN 回源时携带 X-Forwarded-Proto,仅在回源仍为 http 时补跳,避免双跳
    if ($http_x_forwarded_proto = "http") {
        return 301 https://$host$request_uri;
    }
}

常见错误与排查:497、重定向循环、证书链不完整怎么查

客户端用 http:// 访问 443 端口,为什么返回 400 而不是 301?

OpenResty(同 Nginx)在 SSL 监听端口收到明文 HTTP 请求时会置内部状态码 497,最终渲染成 400 Bad Request: The plain HTTP request was sent to HTTPS port。这说明入口 URL 本身写错了,优先修正入口;兜底才用 error_page 497(Nginx 官方文档 error_page 指令,http/server/location 上下文均可用):

# 复现:向 443 端口发明文请求
curl -i http://example.com:443/
# HTTP/1.1 400 Bad Request
# 400 Bad Request: The plain HTTP request was sent to HTTPS port

server {
    listen 443 ssl;
    server_name example.com;
    # 兜底:把误发明文请求 301 到 https,默认无此配置
    error_page 497 =301 https://$host$request_uri;
}

浏览器报 ERR_TOO_MANY_REDIRECTS、curl 报 curl: (47) Maximum (50) redirects followed,怎么定位?

典型链路:SLB/CDN 终止 TLS 后以 HTTP 回源 80 端口,源站又无条件 301 到 https,形成死循环。先在源站本地带代理头复现:

curl -I -H 'X-Forwarded-Proto: https' http://127.0.0.1/index.html
# 若仍返回 301 Location: https://... 说明跳转逻辑没识别回源协议

正确做法是用 map 判断 $http_x_forwarded_proto,仅在确为明文时跳转(map 只能写在 http 上下文):

map $http_x_forwarded_proto $real_scheme {
    default $scheme;   # 无代理头时回落到连接自身协议
    https   https;
    http    http;
}
server {
    listen 80;
    server_name example.com;
    if ($real_scheme = http) {
        return 301 https://$host$request_uri;
    }
}

启动报 nginx: [emerg] duplicate default server for 0.0.0.0:80 怎么办?

同一端口只允许一个 default_server。用 grep -R 'listen 80 default_server' /usr/local/openresty/nginx/conf/ 找出全部命中行,只保留主站那一处,其余改为普通 listen 80;。

启动报 nginx: [emerg] unknown directive “ssl_certificate” 是什么原因?

两种可能:二进制未编译 http_ssl_module,或指令写错层级(ssl_certificate 只能出现在 http/server 块)。先验证:

openresty -V 2>&1 | grep -o with-http_ssl_module
# 有输出 = 支持 SSL;无输出需换官方带 SSL 的发行包

curl 报 SSL certificate problem: unable to get local issuer certificate?

fullchain.pem 缺中间证书。据 OpenSSL 文档,s_client 的 -showcerts 可打印服务端实际发送的证书链:

openssl s_client -connect example.com:443 -servername example.com -showcerts /dev/null 
  | grep -E '^ *[0-9]+ s:'
# 只出现 1 个 s:(叶子证书)即说明链不完整

据 Let’s Encrypt 文档,fullchain 顺序必须是「站点证书 + 中间证书」,当前中间证书为 R10/R11 或 E5/E6,老环境是 R3/E1;用 cat cert.pem chain.pem > fullchain.pem 拼接后 reload 即可。

return 301 https://$server_name$request_uri 为什么跳到错误域名?

因为 $server_name 取自当前匹配的 server 块,在 default_server 兜底时往往是 _ 或空值。三个变量的差异如下:

变量 取值来源 default_server 下无匹配 Host 时
$host 请求行/Host 头,小写且已去端口;缺失时回落 server_name 回落到 server_name,可预测
$server_name 当前 server 块的 server_name 指令值 可能为 _,生成无效跳转
$http_host 原始 Host 头,不做归一化 为空,拼出 https:///path

因此统一写 return 301 https://$host$request_uri;,并在 map $host $allow_host 中为未知 Host 设 default 0,命中 0 时直接 return 444 拒绝,避免被扫描器带入任意域名。

如何验证 OpenResty 强制 HTTPS 已生效?6 个可复现检查

配置写进 nginx.conf 并不等于线上已生效——openresty -t 通过只说明语法没问题,openresty -s reload 成功也只说明老 worker 优雅退出。真正要确认“openresty 强制https 已生效”,必须从客户端视角逐层验证。下面 6 个检查按“从外到内”的顺序排列,每条都给出可直接复制的命令和期望输出。

1. 检查 80 端口的跳转本身是否正确(注意要带上 path 和 query,很多人只测根路径,结果 ?bar=1 被吞掉都不知道):

# -I 只取响应头,不下载正文;路径带 query 用于验证 $request_uri 是否被完整保留
curl -I 'http://example.com/foo?bar=1'

# 期望输出(前三行最关键):
# HTTP/1.1 301 Moved Permanently
# Server: openresty/1.25.3.1
# Location: https://example.com/foo?bar=1

如果 Location 里 query 丢失,说明你写的是 return 301 https://$host$uri;,应改为 $request_uri;如果首行是 HTTP/1.1 302,说明某处 return 302 或 rewrite ... redirect 抢先匹配,301 才是 RFC 7231 定义的永久重定向,可被搜索引擎缓存。

2. 检查最终落地页与跳转次数:

# -L 跟随跳转,-o /dev/null 丢弃正文,-w 打印状态码/最终URL/总耗时
curl -L -o /dev/null -s 
  -w '%{http_code} %{url_effective} %{num_redirects} %{time_total}n' 
  http://example.com

# 期望:200 https://example.com/ 1 0.0xx

%{num_redirects} 应 ≤ 1;出现 2 次以上通常意味着 http→https 之后又跳了一次 www 或尾部斜杠,白白增加一个 RTT。

3. 检查证书链与有效期(据 OpenSSL 文档,-servername 用于发送 SNI,缺了它多证书站点会拿到默认证书):

openssl s_client -connect example.com:443 -servername example.com -tls1_2 /dev/null 
  | openssl x509 -noout -subject -issuer -dates

# 期望:
# subject=CN = example.com
# issuer=C = US, O = Let's Encrypt, CN = R11
# notBefore=...  notAfter=...

Let’s Encrypt 自 2024 年起签发链的中间证书为 R10/R11(RSA)或 E5/E6(ECDSA),notAfter 距今应大于 30 天,否则你的 certbot renew 或 acme.sh 定时任务大概率没跑。

4. 检查 HSTS 头是否真的下发:

curl -sI https://example.com | grep -i strict-transport-security
# 期望:strict-transport-security: max-age=31536000; includeSubDomains

没有输出时,九成是 add_header 写在了 80 端口的 server 块里,或者被更内层 location 的 add_header 覆盖——据 nginx 文档,add_header 遵循“就近继承”原则,子块一旦出现同名指令,父块的全部失效。补上 always 参数可让 4xx/5xx 响应也带该头(RFC 6797 要求 HSTS 只在 HTTPS 响应上生效)。

5. 检查协议版本与 HTTP/2:

curl --http2 -I https://example.com      # 期望首行 HTTP/2 200
nmap --script ssl-enum-ciphers -p 443 example.com
# 期望只列出 TLSv1.2 / TLSv1.3,且不出现 TLSv1.0、TLSv1.1 的 cipher 列表

若 curl 报 HTTP/2 200 缺失,检查 OpenResty 1.25.x 中应写 listen 443 ssl; 加 http2 on;(1.25.3.1 起推荐新语法),旧写法 listen 443 ssl http2; 已标记废弃。加密套件建议对照 Mozilla SSL Configuration Generator 的 intermediate 配置。

6. 检查日志中的跳转占比:默认 combined 格式不含 $scheme,需自定义:

log_format https_probe '$scheme $remote_addr $request_uri $status $request_time';
access_log logs/access.log https_probe;

# 统计 80 端口请求中被 301 掉的比例
awk '$1 == "http" {t++; if ($4 == 301) c++} END {printf "%d/%d = %.1f%%n", c, t, c*100/t}' logs/access.log

该比例应高于 95%;低于此值说明有客户端在用明文 HTTP 拿到 200,通常是某个 location 漏了 return 301,或 if ($scheme = http) 被放在 rewrite 阶段之后。

检查项 命令要点 合格标准 失败最常见原因
80 跳转 curl -I http://…/foo?bar=1 301 + 完整 Location 用了 $uri 丢了 query
落地与次数 curl -L -w '%{num_redirects}' 200,跳转 ≤1 次 www 与斜杠二次跳转
证书 openssl s_client … | x509 -dates notAfter > 30 天 续期 cron 失效
HSTS curl -sI | grep -i strict max-age=31536000 add_header 层级覆盖
协议 curl --http2 -I / nmap HTTP/2 + 仅 TLS1.2/1.3 残留 ssl_protocols 旧值
日志 awk 统计 $scheme/$status 301 占比 >95% 某 location 漏配跳转

如果第 1 项通过但第 2 项失败,问题不在 openresty 强制https 的配置本身,而在后端应用又发了一次 Location;用 curl -v -L 观察每一跳的 < HTTP/1.1 30x 与 < Location: 行即可定位是哪一层在跳。

多域名、反向代理与 CDN 场景的进阶配置

多域名如何统一到同一个规范域名,避免 www 与裸域来回跳?

最常见的故障是两个 server 块互相 301,浏览器直接报 ERR_TOO_MANY_REDIRECTS。正确做法是用 map 在 http 层一次性归一化主机名,再让 80 端口统一跳转。

# OpenResty 1.19+ / nginx 1.11.3+,写在 nginx.conf 的 http 块内
map $host $canonical_host {
    default          $host;          # 未列出的域名保持原样,交给兜底 server
    www.example.com  example.com;    # www 归一到裸域,只跳一次
    example.com      example.com;
    www.example.org  example.org;
}

server {
    listen 80;
    server_name example.com www.example.com example.org www.example.org;
    return 301 https://$canonical_host$request_uri;   # 用 $request_uri 保留路径与查询串
}

注意别写成 $uri,那会丢掉 ?a=1 这类参数。另外 301 会被浏览器长期缓存,调试期建议先用 302,确认无误再换回 301。

反代到 Tomcat / Node 后,应用仍以为是 HTTP 怎么办?

OpenResty 终止 TLS 后,到后端的流量是明文 HTTP,应用侧的 request.isSecure() 或 req.secure 会判成 false,进而触发自己的跳转逻辑形成死循环。必须显式透传协议头:

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host              $host;
    proxy_set_header X-Real-IP         $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;   # https 请求时为 https
}

仅加头还不够,后端要主动信任它——这是最常见的漏配点:

后端 必配项 默认值与坑
Tomcat 8.5+/9/10 server.xml 中加 <Valve className="org.apache.catalina.valves.RemoteIpValve" protocolHeader="X-Forwarded-Proto" protocolHeaderHttpsValue="https"/> 不加则永远返回 http scheme
Node / Express 4.x/5.x app.set('trust proxy', 1); 默认 false,X-Forwarded-Proto 被完全忽略
Spring Boot 2.x+ server.forward-headers-strategy=FRAMEWORK 默认 NONE
PHP-FPM fastcgi_param HTTPS $https if_not_empty; 未传则 $_SERVER['HTTPS'] 为空

套了 CDN 之后,源站日志全是 CDN 节点 IP、跳转还被打断?

Cloudflare 可开启 Always Use HTTPS,让边缘节点直接 301;此时源站 80 只应放行 CDN 回源段,其余一律拒绝,防止有人绕过 CDN 直连。同时用 realip 模块还原真实客户端 IP,否则限流、日志、风控全部失真(ngx_http_realip_module 在 OpenResty 中默认已编译)。

# 完整回源段见 cloudflare.com/ips-v4,此处为示例
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
real_ip_header   CF-Connecting-IP;

server {
    listen 80;
    allow 173.245.48.0/20;
    deny  all;                                  # 非 CDN 来源直接 403
    return 301 https://$canonical_host$request_uri;
}

HSTS 预加载可以随便开吗?

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

提交 hstspreload.org 之前,必须逐个验证所有子域都能 301 到 HTTPS,否则这些子域会直接不可访问:

# 对所有子域批量检查,期望返回 301 且 Location 为 https://
curl -sI http://sub.example.com | head -n 3
curl -sI https://example.com | grep -i strict-transport-security

据 Chromium 的 HSTS Preload 文档,移除申请的处理周期以月计,且要等浏览器版本更新才生效,回滚成本极高;max-age 建议先用 300 秒灰度,确认无混合内容报错后再拉到 31536000。

OCSP Stapling 怎么开、怎么验证?

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/openresty/ssl/fullchain.pem;  # 必须含中间 CA,否则无法验签
resolver 223.5.5.5 119.29.29.29 valid=300s;
resolver_timeout 5s;

# 验证:出现 "OCSP Response Status: successful" 即生效
openssl s_client -connect example.com:443 -servername example.com -status </dev/null 2>/dev/null 
  | grep -A1 "OCSP Response Status"

若返回 no response sent,通常是 ssl_trusted_certificate 只给了叶证书,或服务器出网被防火墙拦截。

怎么在跳转规则被误删时第一时间发现?

用 nginx-lua-prometheus 0.20231114 暴露按 scheme 与 status 维度的计数器:

lua_shared_dict prometheus_metrics 10M;
init_by_lua_block { prometheus = require("prometheus").init("prometheus_metrics") }

log_by_lua_block {
    local c = prometheus:counter("nginx_http_requests_total", "HTTP 请求数", {"scheme", "status"})
    c:inc(1, {ngx.var.scheme, ngx.var.status})
}

据此对 nginx_http_requests_total{scheme="http",status="301"} 建告警:5 分钟窗口内该比例低于 80%,说明 80 端口的 return 301 或 map 归一化已失效,往往是发布时 server 块被覆盖所致。

从 Nginx 迁到 OpenResty:强制 HTTPS 的差异与上线回滚

问:从 nginx 换成 OpenResty,强制 HTTPS 的配置能直接照搬吗?

配置语法可以直接照搬,但运维操作层面有三处不同:一是路径和二进制名,二是 Lua 指令与 return 301 的执行阶段冲突,三是 lua_code_cache 让“改完 reload”这件事变得更敏感。据 OpenResty 官方文档(openresty.org「Installation」与 lua-nginx-module 文档),OpenResty 自带的 nginx 前缀是 /usr/local/openresty/nginx/,而 /usr/local/openresty/bin/openresty 只是对同一份 nginx 二进制的封装,因此 -t、-s reload 的语义与上游 nginx 完全一致,日志也仍然写在 logs/error.log。

项目 上游 nginx(发行版包) OpenResty 默认
配置前缀 /etc/nginx/ /usr/local/openresty/nginx/
可执行文件 /usr/sbin/nginx /usr/local/openresty/bin/openresty
检查配置 nginx -t openresty -t
平滑重载 nginx -s reload openresty -s reload
Lua 代码缓存 无此概念 lua_code_cache on;(生产默认)

问:为什么我加了 return 301,页面却还是被 Lua 接管?

因为 content_by_lua_block 和 return 都注册在 content 阶段,同一个 location 里二选一,同时写会在 -t 阶段直接失败,报错形如:

nginx: [emerg] "return" directive is duplicate, "content_by_lua_block" directive was specified earlier in /usr/local/openresty/nginx/conf/conf.d/site.conf:12
nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test failed

正确做法是把跳转提到 server 级(优先级最高),或改用 access 阶段:

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;   # server 级 return,先于 location 的 content 阶段

    location / {
        content_by_lua_block { ngx.say("never reached on :80") }
    }
}

# 需要按 UA/路径条件跳转时,用 access 阶段,302 是 ngx.redirect 默认值,必须显式写 301
location /old {
    access_by_lua_block {
        ngx.redirect("https://" .. ngx.var.host .. ngx.var.request_uri, 301)
    }
}

注意 lua_code_cache on; 是生产默认值:改完 Lua 跳转逻辑必须 reload,清浏览器缓存没用;开发期临时设 off 会让每个请求重新编译 Lua,开销显著,切勿带到生产。

问:上线和回滚怎么做得可验证?

cd /usr/local/openresty/nginx
# 1) 变更前留档指纹与整包备份
md5sum conf/nginx.conf conf/conf.d/*.conf | tee /tmp/conf-$(date +%F-%H%M).md5
tar czf /tmp/conf-$(date +%F-%H%M).tar.gz conf/
# 2) 灰度:先只改单个 vhost,02:00–04:00 低峰执行
/usr/local/openresty/bin/openresty -t && /usr/local/openresty/bin/openresty -s reload
# 3) 回滚:恢复备份后必须重新 -t 再 reload
cp -a /tmp/conf-20240501-0200/conf/. conf/
/usr/local/openresty/bin/openresty -t && /usr/local/openresty/bin/openresty -s reload

reload 后 5 分钟内盯三项指标:301 响应占比、499/502 计数、证书到期告警;任一异常立即回滚。旧的 80 server 配置建议保留 7 天,因为 CDN 与客户端可能仍缓存旧 DNS/连接,过早删除会让回退路径失效——这也是排查 重定向循环 与 证书续期 问题的前提条件。

优先用 return 301 https://$host$request_uri;,它在 rewrite 阶段前执行,少一次正则匹配,配置也更短。只有需要按路径规则改写时才用 rewrite ^ https://$host$request_uri permanent;,两者对浏览器都返回 301。

多数是 TLS 在 SLB/CDN 终止,源站看到 $scheme 仍是 http,于是 80 端口又 301 到 https,形成循环。用 curl -I -H 'X-Forwarded-Proto: https' http://127.0.0.1 复现,再用 map $http_x_forwarded_proto 判断,只有非 https 时才跳转。

OpenResty 与 Nginx 的 return 301、listen 443 ssl、add_header HSTS 指令基本一致,差异在 OpenResty 的安装路径与 Lua 阶段。Cloudflare 的 Always Use HTTPS 在边缘节点完成跳转,源站 80 可只允许 CDN 回源,避免源站再跳一次。

需要。301 只解决首次访问,浏览器下次仍可能先发 HTTP;HSTS 让浏览器在 max-age 内直接走 HTTPS。首次上线建议 max-age=300 观察 24 小时,确认所有子域可用后再调大到 31536000。

497 表示客户端用 http:// 访问了 443 端口。先检查 URL 与 listen 443 ssl; 是否匹配,必要时加 error_page 497 =301 https://$host$request_uri; 做兜底,但更推荐修正入口或让 80 端口统一 301。

用 $request_uri 而不是 $uri,$request_uri 会保留原始路径与 ?bar=1 查询串。执行 curl -I http://example.com/foo?bar=1,检查 Location 是否为 https://example.com/foo?bar=1 即可。

会。fullchain.pem 缺少中间证书时,部分浏览器和 curl 会报 unable to get local issuer certificate。用 openssl s_client -showcerts 检查链,Let's Encrypt 需把 R10/R11 或 E5/E6 中间证书拼在站点证书后。


本文由 sslgood.com 安全团队基于生产环境实战经验撰写,关键结论均经过技术复核。

内容审核

长期从事 SSL/TLS 证书部署与 HTTPS 运维,负责本站证书选型、安装配置与故障排查内容的编写与审核。