配置 Certbot 自动安装 Let's Encrypt 证书

Configure Certbot to automatically install Let's Encrypt certificate

Posted by Lv Hui on June 24, 2024

安装 certbot 及 certbot nginx插件

1
2
sudo apt update
sudo apt install certbot python3-certbot-nginx

获取证书

假设我们要为example.com和www.example.com这两个域名配置证书

1
sudo certbot --nginx -d example.com -d www.example.com

Certbot会自动配置Nginx以使用获得的SSL证书,并设置自动续订。

配置成功后可看到nginx对应站点配置文件中添加了ssl部分。

1
2
3
4
5
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot 
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot 
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot 
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

检查并重载 nginx 配置

Certbot会修改对应站点的配置文件,先检查一下是否有问题

1
2
sudo nginx -t
sudo systemctl reload nginx

检查 Certbot 的自动续订

Let’s Encrypt 证书的有效期是90天,因此需要设置自动续订,让我们来检查一下 Certbot 的自动续订是否正确配置。

1
sudo certbot renew --dry-run

如果运行成功,则配置没有问题