# Ubuntu 系统 Certbot 安装及 Nginx 配置指南
Certbot 是 Let's Encrypt 官方推荐的 ACME 客户端,可以免费申请 SSL 证书并自动配置 Nginx/Apache。国内用得少,但在境外服务器上是省心的首选。
# 1. 安装 Certbot 及 Nginx 插件
# 更新系统包
sudo apt update && sudo apt upgrade -y
# 安装 Certbot 及 Nginx 插件
sudo apt install certbot python3-certbot-nginx -y
验证安装:
certbot --version
sudo systemctl status nginx
# 2. 申请证书并自动配置 Nginx
sudo certbot --nginx -d your_domain -d www.your_domain
执行后 Certbot 会自动:
- 验证域名所有权(需要 80 端口可访问)
- 下载并安装证书
- 修改 Nginx 配置,添加 443 SSL 监听
- 询问是否将 HTTP 重定向到 HTTPS(选 1 不重定向,选 2 强制跳转)
注意:重定向是你主动选择的,不是 Certbot 强制的。如果后悔了,手动删掉 Nginx 配置里 Certbot 添加的
return 301 https://...那行即可。
# 3. 设置定时自动续期
Ubuntu 安装 Certbot 后通常已自带定时任务,可以手动确认或添加:
# 编辑 crontab
sudo crontab -e
# 添加以下内容(每天凌晨 3 点检查续期,成功后重载 Nginx,输出写入日志)
0 3 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx" >> /var/log/certbot-renew.log 2>&1
验证续期配置是否正常(模拟运行,不实际续期):
sudo certbot renew --dry-run
# 4. 查看日志
| 日志来源 | 路径 |
|---|---|
| Certbot 自身 | /var/log/letsencrypt/letsencrypt.log |
| Crontab 输出 | /var/log/certbot-renew.log(需手动配置重定向) |
| systemd(如适用) | journalctl -u certbot.service |
# 查看最近运行记录
tail -n 200 /var/log/letsencrypt/letsencrypt.log
# 5. 常用命令速查
| 步骤 | 命令 |
|---|---|
| 安装 | sudo apt install certbot python3-certbot-nginx -y |
| 申请证书 | sudo certbot --nginx -d your_domain |
| 查看已管理证书 | sudo certbot certificates |
| 模拟续期测试 | sudo certbot renew --dry-run |
| 手动立即续期 | sudo certbot renew |
# 常见报错
# no "ssl_certificate" is defined
[emerg] no "ssl_certificate" is defined for the "listen ... ssl" directive
原因:配置文件里写了 listen 443 ssl; 但没有配置证书路径。
解决:用 Certbot 重新安装证书让它自动补全配置:
sudo certbot --nginx -d your_domain
或手动在 server 块里添加:
ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem;
# could not build server_names_hash
[emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
原因:域名较长,Nginx 默认哈希桶大小 32 不够用。
解决:编辑 /etc/nginx/nginx.conf,在 http 块内添加:
http {
server_names_hash_bucket_size 64;
# 其他配置...
}
然后重新测试并重载:
sudo nginx -t && sudo systemctl reload nginx
