Nginx server块本身不实现自动续期,但必须满足Certbot验证前提:80端口server块透传/.well-known/acme-challenge/路径,443端口正确引用/etc/letsencrypt/live/下的fullchain.pem和privkey.pem,并通过--deploy-hook或--post-hook触发nginx reload。

配置 Nginx 的 server 块本身不直接实现自动续期,但它必须满足 Certbot 验证和续期的运行前提。关键在于:让 HTTP-01 验证能通、证书路径可被正确引用、且续期后服务能及时加载新证书。
确保 80 端口 server 块支持 ACME 验证
Let’s Encrypt 默认使用 HTTP-01 挑战,要求域名在 80 端口可访问,并能响应 /.well-known/acme-challenge/xxx 路径。Nginx 必须为此开放并透传验证文件:
- 保留一个监听 80 端口的
server块,即使你主站只走 HTTPS - 不要用
return 301 https://$host$request_uri全局跳转——这会中断验证流程 - 为验证路径单独配置 location,例如:
server {
listen 80;
server_name example.com www.example.com;
<pre class='brush:php;toolbar:false;'># ACME 验证专用路径,Certbot 会自动写入文件
location ^~ /.well-known/acme-challenge/ {
root /var/www/html;
try_files $uri =404;
}
# 其他请求才重定向到 HTTPS
location / {
return 301 https://$host$request_uri;
}}
443 端口 server 块要使用标准证书路径
Certbot 自动续期后,证书文件(fullchain.pem 和 privkey.pem)始终保存在固定路径:/etc/letsencrypt/live/example.com/fullchain.pem/etc/letsencrypt/live/example.com/privkey.pem
你的 HTTPS server 块必须直接引用这些路径,不能复制、硬编码或改名:
- 确保
ssl_certificate指向fullchain.pem(不是cert.pem),否则证书链不完整 - 确保
ssl_certificate_key指向privkey.pem - 不要用绝对路径拼接变量,避免路径失效
server {
listen 443 ssl http2;
server_name example.com www.example.com;
<pre class='brush:php;toolbar:false;'>ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 其他 SSL 安全配置(如 TLS 版本、密钥交换等)可按需添加}
续期后需重载 Nginx 配置
Certbot 续期成功不会自动重启 Nginx,必须显式重载配置才能生效。推荐两种方式:
-
使用 --deploy-hook:在
certbot renew中加入钩子命令,例如:sudo certbot renew --deploy-hook "systemctl reload nginx" -
写入 crontab 时带上 reload:例如每日凌晨 3 点执行:
0 3 * * * /usr/bin/certbot renew --quiet --post-hook "/usr/bin/systemctl reload nginx"
验证配置是否就绪
完成配置后,务必测试整个链路是否畅通:
- 运行
sudo nginx -t确认语法无误 - 执行
sudo certbot renew --dry-run模拟续期,看是否通过验证并触发 reload - 检查日志:
sudo journalctl -u certbot -n 20 --no-pager和sudo nginx -t && sudo systemctl status nginx

















