certbot + nginx 给小站配 HTTPS 的极简笔记
给域名配 HTTPS,现在基本就是 certbot 一条命令的事,但模式选错会卡半天。记一下要点。
原理
Let's Encrypt 通过 ACME 协议验证你对域名的控制权。最常用的是 HTTP-01 挑战:证书机构访问 http://你的域名/.well-known/acme-challenge/随机文件,能读到 certbot 预先放好的内容,就证明域名是你的。
standalone 还是 webroot
certbot 有两种验证方式:standalone 是 certbot 自己起一个 HTTP 服务占住 80 端口,适合裸机;webroot 是把挑战文件写进 nginx 已经在服务的目录,适合 80 端口被 nginx 占着的机器。生产机上一律用 webroot,不用停服务。
nginx 里只要留一行:
location /.well-known/acme-challenge/ { root /var/www/html; }
然后签证书:
certbot certonly --webroot -w /var/www/html \
-d example.com -d www.example.com
续期
证书 90 天有效,装 certbot 时自带的 certbot.timer 会自动续期,systemctl list-timers 能看到它。改过验证方式的话,看一眼 /etc/letsencrypt/renewal/ 下对应的配置文件确认写的是 webroot。续期后 nginx 需要 reload 才会加载新证书,没配 deploy hook 的话手动 reload 一次。
nginx 侧
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
}
改完记得 nginx -t 通过再 systemctl reload nginx,别把语法错误的配置直接 reload 上去。