Ubuntu 24.04 Certbot 自动化SSL证书配置指南
简介:
Let's Encrypt 是一个免费、开放、自动化的证书颁发机构(CA),由非营利组织 Internet Security Research Group(ISRG)运营。它提供有效期 90 天的免费 SSL/TLS 证书,任何人都可以申请使用。
Certbot 是 Let's Encrypt 官方推荐的 ACME 客户端,用于自动申请、续期和管理 SSL 证书。它支持多种验证方式(如
--webroot、--nginx、--standalone),可灵活适配不同的服务器环境。环境说明:
- 系统:Ubuntu 24.04
- Web 服务器:Nginx
- 域名:
certbot.xxxx.com- 证书工具:Certbot + Let's Encrypt
一、安装certbot
bash
sudo apt update
sudo apt install certbot -y
安装完成后验证:
bash
certbot --version
二、申请证书
bash
sudo certbot certonly --webroot \
-w /usr/local/nginx-1.26/html \
-d certbot.xxxx.com \
--agree-tos \
--email 123456789@qq.com
参数说明:
-
certonly:只获取证书,不修改 Nginx 配置 -
--webroot:通过网站根目录验证域名所有权 -
-w /usr/local/nginx-1.26/html:换成你的网站根目录路径 -
-d:指定要申请证书的域名 -
--agree-tos:同意 Let's Encrypt 的服务条款 -
--email:用于注册 ACME 账号和接收证书到期提醒
等待过后,我们可以看到证书已经成功申请到了,路径是:
bash
/etc/letsencrypt/live/certbot.xxxx.com/fullchain.pem
/etc/letsencrypt/live/certbot.xxxx.com/privkey.pem
三、添加自动续期定时任务
配置自动续期任务,让证书在到期前自动续签并重载 Nginx,无需手动干预。
1、编辑cron任务
bash
sudo crontab -e
在文件末尾添加一行:
bash
0 3 * * * /usr/bin/certbot renew --quiet --renew-hook "/usr/local/nginx-1.26/sbin/nginx -t && /usr/local/nginx-1.26/sbin/nginx -s reload"
参数说明:
0 3 * * *:每天凌晨 3 点执行certbot renew:检查证书是否需要续期(只有到期前 30 天内才会真正续期)--renew-hook:续期成功后,先检查 Nginx 配置语法,再重载,防止配置错误导致服务中断
2、验证cron任务已添加
bash
sudo crontab -l
3、测试续期流程是否正常
bash
sudo certbot renew --dry-run

看到以上信息,即表示续期流程正常工作。
四、配置 Nginx
配置 Nginx 启用 HTTPS,使证书生效,编辑你的 Nginx 配置文件(我的路径为 /usr/local/nginx-1.26/conf/nginx.conf),写入以下测试内容:
nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name certbot.xxxx.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name certbot.xxxx.com;
ssl_certificate /etc/letsencrypt/live/certbot.xxxx.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/certbot.xxxx.com/privkey.pem;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
然后执行
bash
/usr/local/nginx-1.26/sbin/nginx -t
/usr/local/nginx-1.26/sbin/nginx -s reload
五、验证HTTPS生效
我们来验证一下 HTTPS证书 是否真的生效了,在浏览器里打开 https://certbot.xxxx.com,能看到小锁图标就说明 HTTPS 正常工作了。

如需验证自动续期流程是否真正跑通,可以强制续期一次:
bash
sudo certbot renew --force-renewal --renew-hook "/usr/local/nginx-1.26/sbin/nginx -t && /usr/local/nginx-1.26/sbin/nginx -s reload"
续期后查看证书信息,序列号和到期日期已更新,说明续期流程正常:
bash
sudo certbot certificates
