Apache 使用 Let's Encrypt

借助 certbot 和 Apache 插件,几分钟就能设置好 HTTPS:certbot 获取证书,把它添加到虚拟主机,之后还会自己续期。这里介绍你需要什么,以及可能出什么问题。

前提条件

安装 certbot

# Debian, Ubuntu
sudo apt install certbot python3-certbot-apache

# RHEL, Rocky, Alma (from EPEL)
sudo dnf install epel-release
sudo dnf install certbot python3-certbot-apache

# alternative, always up to date
sudo snap install --classic certbot

获取并安装证书

sudo certbot --apache -d example.com -d www.example.com

第一次运行时,certbot 会询问电子邮件地址并要求同意服务条款。然后它会为 443 端口创建一个虚拟主机(在 Debian 上是 …-le-ssl.conf),添加证书和密钥,并且可以按你的意愿设置从 HTTP 到 HTTPS 的重定向(--redirect)。从 2.0 版起,certbot 创建 ECDSA 密钥;对于非常旧的客户端,可以用 --key-type rsa。

如果不想让 certbot 改动 Apache 配置,certonly 只获取证书:

sudo certbot certonly --webroot -w /var/www/example -d example.com -d www.example.com

之后文件位于 /etc/letsencrypt/live/example.com/。如何自己把它们添加到虚拟主机,见文章 在 Apache 中设置 SSL/TLS。请使用 fullchain.pem,而不是 cert.pem。

自动续期

证书有效期为 90 天。软件包会设置一个 systemd 定时器,每天检查两次,剩余 30 天时开始续期。检查:

systemctl list-timers | grep certbot
sudo certbot renew --dry-run

使用 Apache 插件时,certbot 会在续期后自己重新加载 Apache。使用 certonly --webroot 时,你需要一个部署钩子,否则 Apache 会继续提供旧证书:

sudo certbot renew --deploy-hook "systemctl reload apache2"
# permanently: put a script into /etc/letsencrypt/renewal-hooks/deploy/

Let's Encrypt 自 2025 年起不再发送提醒邮件。为了发现失败,请把服务器添加到 证书到期概览,或者嵌入 SSL 检测 提供的到期徽章。

通配符证书

*.example.com 只能通过 DNS 验证(DNS-01)获取。certbot 需要一个适用于你 DNS 服务商的插件,例如 python3-certbot-dns-cloudflare,或者你可以使用支持非常多服务商的 acme.sh。--manual 不需要插件,但不会自动续期。ACME 助手 会为你的服务商生成命令。

典型错误

最后用 SSL 检测 检查证书链和协议。

FAQ

Let's Encrypt 真的免费吗?

是的。Let's Encrypt 是一个非营利性 CA。这些证书与购买的域名验证证书等效,所有浏览器都接受。

在没有 root 权限的虚拟主机上能用吗?

几乎所有主机商都允许在控制面板中一键启用 Let's Encrypt,例如在 Plesk 或 cPanel 中。只有在你自己的服务器上才需要 certbot。

我能把多个域名放进一个证书吗?

能,使用多个 -d 选项,最多 100 个名称。对于彼此独立的网站,分开的证书更容易管理。

参考资料与文档