浏览器和搜索引擎都期待 HTTPS,而 Let's Encrypt 免费提供证书。在运行 AlmaLinux 9 的 VPS Linux Infrawire 上,Certbot 可以申请证书、修改 Apache 配置并自动续期。同样的步骤也适用于 Rocky Linux 9。
📋 前提条件
- 一台拥有 root 或 sudo 权限的 AlmaLinux 9 VPS(IP 和密码见客户区)。
- 一个域名
example.com,其 A 记录(IPv6 还有 AAAA 记录)指向VPS_IP。请先等待 DNS 生效。 - 已通过 80 端口以 HTTP 提供网站的 Apache(httpd)。
1. 安装 Apache 并开放防火墙
如果还没安装 Apache,请安装并启动。然后在 firewalld 中放行 HTTP 和 HTTPS;Let's Encrypt 验证需要 80 端口。
Bashdnf install -y httpd systemctl enable --now httpd firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --reload firewall-cmd --list-services
2. 为域名创建虚拟主机
Certbot 会查找与你的域名匹配的 ServerName,因此请创建专用的虚拟主机。
Bashmkdir -p /var/www/example.com/public_html echo "Hello" > /var/www/example.com/public_html/index.html
创建 /etc/httpd/conf.d/example.com.conf:
Apache1<VirtualHost *:80> 2 ServerName example.com 3 ServerAlias www.example.com 4 DocumentRoot /var/www/example.com/public_html 5</VirtualHost>
检查语法并重新加载:
Bashapachectl configtest systemctl reload httpd
3. 安装 Certbot 和 mod_ssl
Certbot 来自 EPEL 仓库。mod_ssl 提供 Apache 的 TLS 模块,以及 httpd 监听 443 端口所需的默认证书。
Bashdnf install -y epel-release dnf install -y certbot python3-certbot-apache mod_ssl
4. 申请证书
使用 Apache 插件运行 Certbot。它通过 HTTP 验证域名,写入新的 *-le-ssl.conf 虚拟主机,并可添加从 HTTP 到 HTTPS 的跳转。
Bashcertbot --apache -d example.com -d www.example.com
输入真实的电子邮箱(用于到期提醒),接受条款,并在询问时选择跳转选项。通过 -d 传入的每个域名都必须解析到这台服务器,否则验证会失败。
如果 SELinux 处于 enforcing 模式(默认),标准部署无需特殊处理。不要为了绕过错误而关闭它。
5. 检查自动续期
Let's Encrypt 证书有效期为 90 天。在 AlmaLinux 9 上,该软件包会安装一个 systemd 定时器,每天运行两次,只续期临近到期的证书。
Bashsystemctl list-timers | grep certbot systemctl status certbot-renew.timer
如果列表中没有该定时器,请启用它:
Bashsystemctl enable --now certbot-renew.timer
在不触碰真实证书的情况下模拟续期:
Bashcertbot renew --dry-run
最后一行应提示所有模拟续期均已成功。真实续期之后 Apache 会自动重新加载。
验证
Bashcertbot certificates curl -I https://example.com curl -I http://example.com
第一条命令会列出域名和到期日期。HTTPS 请求应返回 200,HTTP 请求应以 301 跳转到 HTTPS 地址。在浏览器中,锁形图标应显示由 Let's Encrypt 签发的有效证书。要查看完整证书链,可以运行 openssl s_client -connect example.com:443 -servername example.com。
故障排查
- 验证时挑战失败或超时:DNS 还没指向服务器,或 80 端口被封。检查
dig +short example.com、firewall-cmd --list-services以及 VPS 前面的任何防火墙。 - Certbot 找不到匹配的虚拟主机:
/etc/httpd/conf.d/中的ServerName或ServerAlias与传入的域名不一致。修正后运行apachectl configtest再重试。也可以使用certbot certonly --apache并自行配置路径。 - 证书过多或验证失败过多(频率限制):Let's Encrypt 会限制重复尝试。请先用
certbot --apache --dry-run测试,并等待一段时间再重试。 - 安装后 443 端口无法访问:firewalld 未开放 HTTPS,或 httpd 未重新加载。运行
firewall-cmd --permanent --add-service=https、firewall-cmd --reload和systemctl restart httpd。
🔐 你在 AlmaLinux 9 上的 Apache 网站现在已启用 HTTPS,并会自动续期证书。