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

Apache 强制 HTTPS 怎么做?从 301 跳转链路到 HSTS 的完整配置与排查

apache 强制https — Apache 强制 HTTPS 怎么做?从 301 跳转链路到 HSTS 的完整配置与排查
核心结论

Apache 强制 HTTPS 的核心做法是:在 httpd 2.4 的 *:80 VirtualHost 中返回 301 到 https://,在 *:443 启用 SSLEngine 并下发 HSTS;配置后执行 apachectl configtest 看到 Syntax OK 再 reload。 最小可用配置:RewriteEngine On、RewriteCond %{HTTPS} !=on、RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L];调试期把 R=301 改为 R=302,确认链路后再换 301。 HSTS 参数从 max-age=300 起测,稳定后设 max-age=31536000; includeSubDomains;preload 需至少 31536000 秒并单独提交,回滚用 max-age=0。 验证命令:curl -sS -o /dev/null -w '%{http_code} %{redirect_url}' http://example.com/abc 应返回 301 https://example.com/abc;curl -I https://example.com 应看到 strict-transport-security 头。 常见报错 AH00124 多为 301 循环,ERR_TOO_MANY_REDIRECTS 多发生在 CDN/负载均衡终止 TLS 后 %{HTTPS} 恒为 off;需用 X-Forwarded-Proto 与 RemoteIPHeader 判断真实协议。

为什么 Apache 强制 HTTPS 会失效?先看 301 跳转链路和 6 个根因

Apache 强制 HTTPS 的本质,并不是“证书装好就自动生效”。证书只参与 *:443 上的 TLS 握手;当用户输入 http://example.com 时,请求先落到 *:80,必须由 Apache 自己返回一个 Location 指向 https:// 的 301,浏览器才会重发请求。据 RFC 7231 §6.4.2,301 表示永久重定向,且默认允许缓存,Chrome、Firefox 会把结果写入磁盘缓存;因此调试阶段应先用 R=302 确认链路,再换 R=301,否则一次写错的跳转会持续影响你数小时。

一个能正常工作的最小配置骨架(适用于 Apache httpd 2.4,RHEL/CentOS 中放在 /etc/httpd/conf.d/ssl-redirect.conf,Debian/Ubuntu 中放在 /etc/apache2/sites-enabled/):

# 80 端口:只负责跳转,不再提供任何明文内容
<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    # 关键:先放行 ACME HTTP-01 验证路径,否则续签请求会被自己跳死
    RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/
    RewriteRule ^/(.*)$ https://example.com/$1 [R=301,L]
</VirtualHost>

# 443 端口:真正提供内容
<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>

排查时先运行下面几条命令,它们能定位下面 6 个根因中的大部分:

curl -I  http://example.com      # 首行必须是 HTTP/1.1 301 Moved Permanently;返回 200 即根因 1
curl -IL http://example.com      # 跟随整条链路,出现 2 次以上 301 说明存在多余跳转
httpd -M | grep rewrite_module   # 无输出 = mod_rewrite 未加载(Debian 用 apache2ctl -M)
httpd -S                         # 检查 VirtualHost 匹配,确认请求落到哪个 ServerName
根因 典型现象 修复要点
1. 只配了 *:443 的 SSLEngine,*:80 没有任何 Redirect 或 RewriteRule curl -I http:// 返回 200 补 *:80 虚拟主机,见上方骨架
2. mod_rewrite 未加载 httpd -M 无 rewrite_module,日志报 Invalid command 'RewriteEngine' 确认 LoadModule rewrite_module modules/mod_rewrite.so;RHEL 包名 httpd、模块目录 /etc/httpd/modules,Debian 包名 apache2、目录 /usr/lib/apache2/modules,可用 a2enmod rewrite
3. CDN 或负载均衡已终止 TLS,回源到 Apache 是明文 HTTP %{HTTPS} 恒为 off,条件判断失效甚至无限重定向 用 X-Forwarded-Proto 判断,见下方片段
4. .htaccess 放错目录,或目录未开 AllowOverride 规则完全不生效,或访问直接 403 Apache 2.4 默认 AllowOverride None,需在 <Directory /var/www/html> 中设 AllowOverride All;生产环境更推荐直接写主配置,省掉每次请求递归读取 .htaccess 的开销
5. Let’s Encrypt HTTP-01 验证路径被 301 到尚未就绪的 HTTPS 续签报 Invalid response ... : 404 在 301 规则前排除 /.well-known/acme-challenge/,或改用 DNS-01
6. 跳转链路过长(http://www → https://www → https:// 裸域) curl -IL 出现多段 301,每段都被浏览器永久缓存 一条规则直接跳到最终主机名,HSTS 的 max-age 从 300 秒起步,验证后再按 Mozilla 推荐值逐步拉长

根因 3 的完整写法(需 mod_remoteip,Apache 2.4 自带):

# 只信任自家反代网段,防止客户端伪造 X-Forwarded-For
RemoteIPHeader X-Forwarded-For
RemoteIPTrustedProxy 10.0.0.0/8
RemoteIPTrustedProxy 192.168.0.0/16

# 让 %{HTTPS} 与后端脚本(如 PHP 的 $_SERVER['HTTPS'])都能识别真实协议
SetEnvIf X-Forwarded-Proto https HTTPS=on

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*)$ https://example.com/$1 [R=301,L]

Apache 强制 HTTPS 的完整实操步骤:从证书检查到全站 301(按编号执行)

下面 6 步在 Apache 2.4.58 / 2.4.59 + OpenSSL 3.0/3.2 上验证通过,命令同时标注 RHEL/CentOS(httpd)与 Debian/Ubuntu(apache2)的差异。整个流程的核心原则是:先验证证书与模块,再改配置,最后只做平滑重载——顺序错了,排查成本会翻倍。

步骤 1:确认版本并备份配置。mod_ssl 的 Protocols h2 需要 2.4.10 以上,HSTS 依赖 mod_headers;OpenSSL 3.x 才有较完整的 TLS 1.3 支持。

# 版本核对:应显示 Server version: Apache/2.4.58 (Unix) 或 2.4.59
httpd -v            # Debian/Ubuntu 用 apache2 -v,输出格式相同
openssl version     # 建议 OpenSSL 3.0.x / 3.2.x;1.1.1 亦可但已停止维护

# 备份(带日期后缀,便于回滚)
cp -a /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak.$(date +%F)
cp -a /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.bak.$(date +%F)
# Debian/Ubuntu 对应文件
cp -a /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf.bak.$(date +%F)
cp -a /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak.$(date +%F)

步骤 2:检查证书与私钥是否匹配。据 Let’s Encrypt 文档,证书有效期固定为 90 天,且默认通过 http-01 校验,因此证书与私钥不匹配是强制 HTTPS 后最常见的“站点打不开”原因。

cd /etc/letsencrypt/live/example.com

# 两行输出的 MD5 必须完全一致;不一致时 Apache 报 SSL 握手失败
openssl x509 -noout -modulus -in fullchain.pem | openssl md5
openssl rsa  -noout -modulus -in privkey.pem  | openssl md5

# ECDSA 私钥没有 modulus,改用公钥比对
# openssl x509 -noout -pubkey -in fullchain.pem | openssl md5
# openssl pkey -in privkey.pem -pubout | openssl md5

# SAN 必须同时覆盖裸域与 www:DNS:example.com, DNS:www.example.com
openssl x509 -noout -text -in fullchain.pem | grep -A1 "Subject Alternative Name"
openssl x509 -noout -dates -in fullchain.pem   # notBefore / notAfter

步骤 3:加载必要模块。RHEL 系在 httpd.conf 中确认以下三行未被注释;Debian 系用 a2enmod ssl rewrite headers 后自动生成。

LoadModule ssl_module modules/mod_ssl.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule headers_module modules/mod_headers.so

# 验证:三行都应带 (shared)
httpd -M | grep -E 'ssl|rewrite|headers'

步骤 4:配置 *:80 的 301 跳转。用 RewriteRule 而非 Redirect permanent,是为了能排除 ACME 校验路径——否则证书续期会被自己的跳转挡死。

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    RewriteEngine On
    # 放行 http-01 校验,避免 certbot renew 失败
    RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/
    RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</VirtualHost>

若想用 https://%{HTTP_HOST}%{REQUEST_URI} 保留用户原始域名,必须先加 Host 白名单,否则会形成开放重定向(Host 头注入):RewriteCond %{HTTP_HOST} ^(www.)?example.com$ [NC]。注意 REQUEST_URI 已包含查询串,无需再加 %{QUERY_STRING}。

步骤 5:配置 *:443 的 TLS 与 HSTS。Protocols 默认值仅为 http/1.1,要启用 HTTP/2 必须显式声明;mod_http2 未加载时 Apache 会忽略 h2 并回退。

<VirtualHost *:443>
    ServerName example.com
    ServerAlias www.example.com
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    Protocols h2 http/1.1
    # env=HTTPS 保证只在加密连接返回该头;RFC 6797 规定非 HTTPS 响应中的 HSTS 会被浏览器忽略
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS
</VirtualHost>

HSTS 的 max-age 没有服务端默认值,不设置即不下发。Mozilla 服务器端 TLS 指南建议生产环境至少 1 年,但首次上线请按阶段爬坡,因为浏览器一旦缓存就无法撤回:

阶段 max-age 附加参数 适用场景
试运行 300(5 分钟) 无 首次上线,观察混合内容告警
过渡 86400(1 天) includeSubDomains 谨慎开启 全站资源已确认走 HTTPS
稳定 31536000(1 年) includeSubDomains 所有子域均已支持 HTTPS
预加载 63072000(2 年) + preload 已提交 HSTS Preload List,几乎不可逆

步骤 6:语法检查与平滑重载。restart 会掐断现有 keep-alive 连接,而 reload/graceful 让旧进程处理完存量请求再退出。

apachectl configtest          # 或 httpd -t;必须看到 Syntax OK
systemctl reload httpd        # Debian/Ubuntu: systemctl reload apache2
# 无 systemd 或需绝对零中断时:
apachectl graceful

# 验证跳转与 HSTS 是否生效
curl -sI http://example.com | head -3          # 期望 HTTP/1.1 301 + Location: https://example.com/
curl -sI https://example.com | grep -i strict-transport-security

检查失败时的典型输出是 AH00526: Syntax error on line 42 of /etc/httpd/conf.d/ssl.conf 或 SSLCertificateFile: file '/etc/letsencrypt/live/...' does not exist——前者多半是漏写 </VirtualHost>,后者通常是 SELinux 未放行 /etc/letsencrypt(需 chcon -R -t cert_t)。此外确认 firewalld/ufw 已放行 443,否则 301 会把用户送到一个连不上的端口。

Apache 强制 HTTPS 配置与命令示例:httpd 2.4 + OpenSSL 3.x 可直接复制

把全站流量推到 HTTPS,在 httpd 2.4 上通常分两步:80 端口做 301 跳转(链路最短、最省资源),443 站点补 HSTS 让浏览器记住”只走 HTTPS”。以下配置适用于 Apache httpd 2.4.x + OpenSSL 3.x,需启用 mod_ssl、mod_alias、mod_headers(mod_rewrite 视方案而定)。

80 端口最省事的写法是什么?用 mod_alias 的 Redirect permanent,一行搞定,无需重写引擎:

# /etc/httpd/conf.d/redirect.conf —— 只做跳转,不提供任何页面内容
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    # Redirect permanent 等价于 301;目标不带路径时,原 URI 会被追加到目标后面
    Redirect permanent / https://example.com/
</VirtualHost>

据 Apache HTTP Server 2.4 官方文档(mod_alias),当目标 URL 不含路径部分时,客户端请求的路径会被原样附加——http://example.com/abc?x=1 会跳到 https://example.com/abc?x=1,查询串默认保留。该指令自 1.3 起存在,2.4 行为未变。注意 mod_alias 与 mod_rewrite 混用容易出现”规则没生效”的假象,同一 VirtualHost 内建议二选一。

要保留 ACME 验证路径不被跳转怎么办?Let’s Encrypt 的 http-01 校验必须能在 80 端口读到 /.well-known/acme-challenge/ 下的文件,此时改用 mod_rewrite 做排除:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    RewriteEngine On
    # 放行 ACME 校验路径,否则证书续期会拿到 301 而失败
    RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/
    RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</VirtualHost>

两个易踩的坑:[L] 只终止本轮重写,规则必须排在该 VirtualHost 内其他 RewriteRule 之前;写在 .htaccess 里时父目录规则先执行,同样可能被拦截。另外 %{REQUEST_URI} 已包含完整路径,无需再拼 %{QUERY_STRING}。

443 站点的关键片段怎么写?

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html
    SSLEngine on
    # Apache 2.4.8 起 SSLCertificateChainFile 已弃用,中间证书直接并入 fullchain.pem
    SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
    # Protocols 需 2.4.17+ 与 mod_http2,默认值不含 h2
    Protocols h2 http/1.1
    # env=HTTPS 保证只在 TLS 连接上发送,避免明文响应带上 HSTS 头
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS

TLS 参数按 Mozilla SSL Configuration Generator 的 intermediate 档:SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1、SSLHonorCipherOrder off、SSLSessionTickets off,密码套件用其给出的 OpenSSL 1.1.1+/3.x 串(ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:…:DHE-RSA-AES256-GCM-SHA384)。OpenSSL 3.x 的 SECLEVEL=2 已默认禁掉弱套件,但显式声明 SSLProtocol 仍必要,因为发行版的 openssl.cnf 未必同步。

只有 .htaccess 权限,或站点在反向代理后面呢?

# 普通场景
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# 位于 Nginx/ALB 之后:%{HTTPS} 永远是 off,直接判断会死循环
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

反代场景务必同时用 Require ip 或防火墙只信任代理 IP 段,否则客户端可伪造 X-Forwarded-Proto 绕过跳转。

写法 生效位置 保留原路径 适用场景 注意
Redirect permanent / VirtualHost / server config 是(目标无路径时自动追加) 纯跳转,性能最好 不能放行 ACME 路径
RewriteRule … [R=301,L] VirtualHost / .htaccess 是(手工拼 %{REQUEST_URI}) 需排除路径、按条件跳转 规则顺序敏感
%{HTTPS} !=on .htaccess 是 无权限改主配置的共享主机 每次请求都读 .htaccess

怎么验证配好了?两条 curl 就够,看状态码、Location 和 HSTS 头是否齐全:

curl -I http://example.com/abc
# 期望:HTTP/1.1 301 Moved Permanently
#       Location: https://example.com/abc

curl -I https://example.com
# 期望:HTTP/2 200
#       strict-transport-security: max-age=31536000; includeSubDomains

如果第一条返回 200 或 302,检查是否 80 端口另有 DocumentRoot 抢先匹配、或 Redirect 写在 <Directory> 里被覆盖;如果第二条没有 HSTS 头,多半是 mod_headers 未加载,或 env=HTTPS 条件下变量未置位(反向代理场景下 %{HTTPS} 为 off,需改用 Header always set … 不带 env 或用 SetEnvIf X-Forwarded-Proto https HTTPS=on)。

Apache 强制 HTTPS 方案怎么选?mod_rewrite、Redirect、HSTS 与代理层对比表

先说结论:Apache 强制 HTTPS 并没有“唯一正确”的方案,只有“放在哪一层做跳转”的选择。判断顺序通常是——TLS 在不在 Apache 上终止?你能不能改主配置?站点是否已经全量 HTTPS?下面这张表把五种常见做法放在一起对比,后文再给可直接复制的配置。

方案 配置方式 适用场景 优点 风险/注意
mod_rewrite RewriteRule ^ https://... [R=301,L] 单机 Apache、需要排除 ACME 路径 规则灵活,可按 URI/UA/Header 加条件 规则顺序错误会自我循环,日志出现 AH00124
Redirect Redirect permanent / https://example.com/ 全站简单跳转 配置短,只需 mod_alias 复杂例外得改用 RedirectMatch 正则
.htaccess RewriteEngine On + RewriteCond %{HTTPS} !=on 无 root 权限、共享主机 不动主配置,可随代码发布 AllowOverride None 时完全无效,且有每请求开销
HSTS Header always set Strict-Transport-Security ... env=HTTPS HTTPS 已稳定运行的站点 浏览器后续访问不再发明文请求 首次访问仍依赖 301;preload 几乎不可回滚
CDN/负载均衡 边缘 301,或按 X-Forwarded-Proto 判断 多节点、TLS 在边缘终止 减少回源、入口统一 回源走 HTTP 时 %{HTTPS} 恒为 off,会误判

单机 Apache:优先在 *:80 的 VirtualHost 里用 Redirect 或 RewriteRule。据 Apache HTTP Server 2.4 文档,Redirect permanent 与 R=301 都返回 301,区别只在是否需要正则条件。下面的写法把 ACME http-01 校验路径排除在外——据 Let’s Encrypt 文档,证书续期时验证服务器必须能通过 HTTP 访问 /.well-known/acme-challenge/,否则续期直接失败:

# Apache 2.4,写入 *:80 的 VirtualHost 内;规则尽量控制在 10 条以内并放在最前
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    RewriteEngine On
    # 排除 ACME 校验与健康检查,避免证书续期被 301 打断
    RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/
    # R=301 永久重定向;L 命中后停止解析后续规则(防止循环)
    RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</VirtualHost>
# 更短的等价写法:仅用 mod_alias,无需 mod_rewrite
<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/          # permanent = 301
    # 需要例外路径时用 RedirectMatch(PCRE 负向断言)
    # RedirectMatch permanent ^/(?!.well-known/acme-challenge/)(.*)$ https://example.com/$1
</VirtualHost>

HSTS 是补充,不是 301 的替代品。据 RFC 6797,浏览器只在 HTTPS 响应中处理该头,所以它救不了第一次明文访问;而 max-age 单位为秒,没有默认值——不发送该头就等于关闭。申请 preload 需 max-age≥31536000 且带 includeSubDomains 与 preload,回滚只能用 max-age=0 覆盖 HTTPS 响应,已被预加载的域名在浏览器内置列表中移除很慢。

# Apache 2.4,放在 *:443 的 VirtualHost 内
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS
# env=HTTPS 确保只在 HTTPS 响应里下发,避免 80 端口误发;申请 preload 时追加 ; preload

TLS 在 CDN/ALB 终止时,%{HTTPS} 判断的是 Apache 自身连接,回源为 HTTP 就恒为 off,用它做条件会导致无限 301(日志里是 AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error)。此时应改看 X-Forwarded-Proto,并用 mod_remoteip 还原客户端 IP:

RewriteEngine On
# 边缘已做 301 时这层只是兜底;注意 CDN 必须覆盖写入该头,不能透传客户端伪造值
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

性能与版本差异。.htaccess 会让 Apache 对每个请求逐级读取目录下的配置文件,AllowOverride None(httpd.conf 默认值)能彻底关掉这条路径;QPS 高、静态资源多时优先写主配置或直接放边缘。Apache 2.4 的授权语法是 Require all granted,不再是 2.2 的 Order allow,deny;SSLCertificateChainFile 自 2.4.8 起弃用,证书链直接追加进 SSLCertificateFile 指向的文件。TLS 侧建议 SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1,只保留 TLS 1.2/1.3——这与 Mozilla SSL Configuration Generator 的 intermediate 配置一致,也能让 HSTS 的安全边界真正成立。

Apache 强制 HTTPS 上线后最常见的四类故障,几乎都能用一条命令定位。先记住这个排查顺序:先看跳转链,再看 TLS 握手,再看目录权限,最后看页面资源。

1)AH00124:301 跳转循环怎么破?

错误日志出现 AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error.,说明跳转成环,浏览器端表现为 ERR_TOO_MANY_REDIRECTS。用 curl 看清 Location 链(-L 默认最多跟 10 跳,与 Apache 内部限制一致):

curl -I -L -v https://example.com/ 2>&1 | grep -E '^(HTTP/|< [Ll]ocation)'
# 输出若为 https -> https 反复,说明 443 虚拟主机里也写了无条件 RewriteRule

三类根因:① *:80 与 *:443 两个 VirtualHost 里都放了无条件 RewriteRule ^ https://...;② 反向代理回源用 HTTP,后端又跳 HTTPS;③ TLS 在负载均衡器终止,后端 Apache 收到的仍是 http,导致 RewriteCond %{HTTPS} !=on 永远为真。正确写法(Apache 2.4,mod_rewrite 默认随包启用):

<VirtualHost *:80>
  RewriteEngine On
  # 已由代理标记为 HTTPS 的请求不再跳转,打断循环
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
</VirtualHost>

若用 SetEnvIf 方案,则写 SetEnvIf X-Forwarded-Proto https HTTPS=on,让 %{HTTPS} 在 TLS 终止后仍成立。同时建议在 Apache 2.4 中配置真实客户端 IP:

RemoteIPHeader X-Forwarded-For
RemoteIPTrustedProxy 10.0.0.0/8
# RemoteIPTrustedProxy 可多次出现;不加则日志与访问控制全部拿到代理 IP

2)混合内容:HSTS 救不了首屏

控制台报 Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http://...',说明 HTML 里硬编码了 http 资源。注意:HSTS 只对后续导航与子资源生效,无法修复当前页面的混合内容。两条路:改资源 URL(WordPress 用 Better Search Replace 批量替换 http://,务必先备份数据库),或加响应头:

Header always set Content-Security-Policy "upgrade-insecure-requests"

3)证书不匹配与 SSL 版本号错误

报错 含义 定位命令
AH01909: ... server certificate does NOT include an ID which matches the server name 证书 SAN 不含该域名,或 SNI 选错证书 openssl x509 -in cert.pem -noout -text | grep -A1 'Subject Alternative Name'
curl: (35) error:0A00010B:SSL routines::wrong version number / SSL_ERROR_RX_RECORD_TOO_LONG 用 HTTPS 访问了 80 端口,或 443 未监听 ss -lntp | grep 443

前者需重新签发含 example.com 与 www.example.com 的证书(据 Let’s Encrypt 文档,默认证书已包含全部申请域名作为 SAN);后者依次检查 Listen 443、firewall-cmd --add-service=https --permanent && firewall-cmd --reload、云安全组放行 443,最后验证握手:

openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -dates

4)AH01630 与 403

AH01630: client denied by server configuration 是 Apache 2.4 的授权拒绝。旧版 Order allow,deny 语法已废弃,改用:

<Directory "/var/www/html">
  Require all granted   # 2.4 默认策略为 Require all denied,漏写即 403
</Directory>
namei -l /var/www/html/index.php   # 目录需 755、文件 644,属主与运行用户一致
getenforce                          # Enforcing 时查看拒绝记录
ausearch -m avc -ts recent

不要用 chmod 777 绕过——它会让 mod_php/php-fpm 之外的进程也能改写站点文件。SELinux 场景用 chcon -R -t httpd_sys_content_t /var/www/html 或 setsebool -P httpd_can_network_connect 1 精准放行。

如何验证 Apache 强制 HTTPS 已生效?curl、openssl、浏览器与日志四步确认

配置完 apache 强制https 之后,最容易翻车的不是规则写错,而是”看起来生效了”。下面四步按从快到慢排列,每步都给出可复制的命令和期望输出——任何一步的输出和期望不一致,问题就一定在那一层。

第一步:用 curl 验证 80 端口的 301 跳转目标

# -o /dev/null 丢弃响应体;%{redirect_url} 需要 curl >= 7.9.1
curl -sS -o /dev/null -w '%{http_code} %{redirect_url}n' http://example.com/abc
# 期望输出:301 https://example.com/abc
# 若输出 200        → 80 端口的 VirtualHost 里没有 Redirect 或 RewriteRule
# 若输出 301 ...://www.example.com/abc → 跳错了主机名,HSTS 与证书都覆盖不到主域

再确认根路径的 Location 头是否精确:

curl -sSI http://example.com | grep -Ei '^(HTTP/|Location)'
# 期望:HTTP/1.1 301 Moved Permanently
#       Location: https://example.com/        ← 必须是 https,且不要带 :8443 之类错误端口

第二步:验证 HTTPS 响应与 HSTS 头

curl -sSI https://example.com | grep -Ei '^(HTTP/|strict-transport-security)'
# 期望:HTTP/2 200
#       strict-transport-security: max-age=31536000; includeSubDomains

curl -sSI https://www.example.com | grep -Ei '^(HTTP/|Location)'
# 期望:301 指向 https://example.com/(或反之,但必须与证书 SAN 一致)

据 RFC 6797 第 7.2 节,浏览器只接受通过安全传输收到的 STS 头,所以这段头必须由 443 的 VirtualHost 下发(Apache 2.4 中用 Header always set Strict-Transport-Security,依赖 mod_headers)。用 curl -I http://... 检查 HSTS 头毫无意义。

第三步:用 openssl 验证证书链与协议版本

# -servername 触发 SNI(见 OpenSSL 文档 s_client 一节),缺了它多站点服务器会返回默认证书
openssl s_client -connect example.com:443 -servername example.com -tls1_2 /dev/null 
  | openssl x509 -noout -subject -issuer -dates
# 期望:subject=CN = example.com(SAN 含 www.example.com)
#       issuer=C = US, O = Let's Encrypt, CN = R11
#       notBefore / notAfter 覆盖当前时间

openssl s_client -connect example.com:443 -servername example.com -tls1_3 /dev/null | grep 'Protocol'
# 期望:Protocol  : TLSv1.3
openssl s_client -connect example.com:443 -tls1 /dev/null | grep -c 'Cipher is'
# 期望:0(握手失败),说明 TLS 1.0 已关闭;同理测 -tls1_1

第四步:浏览器与日志确认

  • DevTools → Network 勾选 Preserve log,访问 http:// 应看到一条 301 紧跟一条 200;Console 不应出现 Mixed Content 警告;Security 面板显示证书有效。
  • Chrome 在 chrome://net-internals/#hsts 的 Query HSTS/PKP domain 里输入域名,能查到 max-age 即表示浏览器已记录;Firefox 在 about:preferences#privacy 开启 HTTPS-Only 模式复核。
  • 日志侧:tail -f /var/log/httpd/access_log | grep ' 301 ' 应出现 "GET /abc HTTP/1.1" 301;grep -i ssl /var/log/httpd/error_log 若持续刷 AH01909: RSA certificate configured for www.example.com:443 does not include an ID which matches the server name,说明 ServerName/ServerAlias 与证书 SAN 不匹配;apachectl -S 用来确认 *:80 与 *:443 的 VirtualHost 归属和默认站点。
验证层 命令 通过标准 失败通常意味着
跳转 curl -sS -o /dev/null -w '%{http_code} %{redirect_url}' 301 + https 同主机同路径 Redirect/RewriteRule 缺失或主机名写错
HSTS curl -sSI https://… 含 max-age=31536000; includeSubDomains mod_headers 未启用或 Header 写在 80 的 vhost 里
证书 openssl s_client -servername … issuer 为预期 CA,日期有效 SNI 未匹配 / 中间证书缺失
协议 nmap --script ssl-enum-ciphers -p 443 example.com 仅 TLS 1.2、TLS 1.3 SSLProtocol 未显式排除 TLSv1/1.1

外部复核建议用 Qualys SSL Labs 的 ssltest 看整链评分(A 及以上通常要求关闭 TLS 1.0/1.1 且启用 HSTS);curl --http2 -I https://example.com 可单独确认 h2 协商是否真的开了,而不是只看到 HTTP/1.1 200 就以为万事大吉。

正式环境用 301,因为 RFC 7231 定义 301 为永久重定向,浏览器和搜索引擎会缓存;调试阶段先用 302,确认 Location、证书和代理链路无误后再换 301。若换回 301 后发现错误,清理浏览器缓存或用无痕窗口复测。

常见原因是 HTTP-01 验证路径被 301 到 HTTPS 后证书未就绪,日志出现 Invalid response … 404;在 *:80 的 RewriteRule 前加 RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/,或改用 DNS-01。续签后用 certbot renew –dry-run 验证。

两者目标一致,都是让 HTTP 返回 301;Apache 常用 Redirect permanent 或 mod_rewrite 的 [R=301,L],Nginx 常用 return 301 https://$host$request_uri。差异主要在配置语法、模块加载和 .htaccess 支持,Apache 的 .htaccess 每请求递归读取,主配置或边缘 301 通常更易维护。

这通常表示 301 循环:例如 CDN 已终止 TLS,回源到 Apache 是 HTTP,而 Apache 又用 %{HTTPS} 判断并再次 301;或 *:80 与 *:443 都无条件跳转。解决方式是使用 X-Forwarded-Proto 判断真实协议,并用 RemoteIPHeader/RemoteIPTrustedProxy 限制可信代理,再用 curl -I -L -v 查看跳转链。

这是混合内容,不是 301 没生效;HSTS 只影响后续访问,不能修复首屏 http:// 资源。先改数据库和模板中的资源 URL,再考虑 Content-Security-Policy: upgrade-insecure-requests;用浏览器 Console 搜索 Mixed Content 定位具体 URL。

可以,在 HTTPS 响应中返回 Strict-Transport-Security: max-age=0 覆盖旧策略,但浏览器要能正常访问 HTTPS 才会更新;如果已加入 preload 列表,移除需要向浏览器厂商提交并等待列表更新。首次上线建议从 max-age=300 开始,稳定后再设 31536000。


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

内容审核

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