# 安装 Certbot

使用适合你的 Web 服务器的插件(例如 NginxApache

安装 Certbot 和 Nginx 插件:

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

如果使用的是 Apache,则安装:

sudo apt install certbot python3-certbot-apache

# 申请证书

使用 Nginx

sudo certbot --nginx

给新的域名申请证书:

sudo certbot --nginx -d example.com

使用 Apache :

sudo certbot --apache

如果使用的是其他 Web 服务器(例如自己搭建的 Node.js 服务),使用 webroot 模式(将验证文件放在某个可被访问的目录中):

sudo certbot certonly --webroot -w /var/www/html -d yourdomain.com -d www.yourdomain.com

-w 后面是你网站根目录的路径

# 证书路径

申请成功后,证书和私钥会保存在:

  • 证书路径: /etc/letsencrypt/live/yourdomain.com/fullchain.pem

  • 私钥路径: /etc/letsencrypt/live/yourdomain.com/privkey.pem

# 更新证书

certbot renew

# 设置自动续期

Certbot 默认安装后会自动添加一个 cron 任务或 systemd timer 来每 12 小时检查一次证书是否需要续期。你可以验证自动续期是否工作:

sudo systemctl list-timers | grep certbot

手动模拟续期测试

sudo certbot renew --dry-run

如果这个命令执行成功,说明自动续期是 OK 的。

# (可选)Nginx 配置自动重载

有些情况下, Certbot 不会自动 reload Nginx 或其他服务。你可以自己设置一个钩子:

sudo vim /etc/letsencrypt/renewal-hooks/post/reload-nginx.sh

内容如下

#!/bin/bash
systemctl reload nginx

保存后设置权限:

sudo chmod +x /etc/letsencrypt/renewal-hooks/post/reload-nginx.sh

# 删除网站证书

Certbot 提供了内建命令用于删除某个域名的证书。

sudo certbot delete

运行后会出现一个交互式菜单,让你选择要删除的证书:

Which certificate would you like to delete?
-------------------------------------------------------------------------------
1: yourdomain.com
2: otherdomain.com
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):

选择对应数字,然后回车即可。

Certbot 会在 /etc/letsencrypt/renewal/ 目录下保存每个证书的续期配置文件。删除证书时,这个文件通常也会一并被删除。

你可以手动检查:

sudo ls /etc/letsencrypt/renewal/

如果仍然存在某个域名的 .conf 文件(如 yourdomain.com.conf ),你可以手动删除它:

sudo rm /etc/letsencrypt/renewal/yourdomain.com.conf
更新于