使用 Let's Encrypt 生成免费 SSL 证书主要有两种常用方式:通过 certbot
工具或使用 acme.sh
脚本。以下是详细步骤:
方法一:使用 Certbot(官方推荐)
1. 安装 Certbot
根据操作系统选择安装命令:
# Ubuntu/Debian
sudo apt update
sudo apt install certbot
# CentOS/RHEL
sudo yum install certbot
# 或使用 Snap(通用)
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
2. 生成证书
方式一:自动验证(需要服务器开放80/443端口)
# 为域名 example.com 和 www.example.com 生成证书
sudo certbot certonly --standalone -d example.com -d www.example.com
--standalone
:使用临时内置的 Web 服务器验证域名所有权。需确保防火墙允许80(HTTP)和443(HTTPS)端口。
方式二:手动验证(无需开放端口)
sudo certbot certonly --manual --preferred-challenges dns -d example.com -d www.example.com
需按提示在域名DNS中添加TXT记录验证。
3. 证书位置
生成的证书通常位于:
/etc/letsencrypt/live/example.com/
├── cert.pem # 证书
├── chain.pem # 中间证书
├── fullchain.pem # 证书+中间证书
└── privkey.pem # 私钥
4. 自动续期
Let's Encrypt 证书有效期为90天,设置自动续期:
sudo certbot renew --dry-run # 测试续期
sudo crontab -e
添加定时任务(每月续期):
0 0 1 * * /usr/bin/certbot renew --quiet
更简单的方法,可以自动选择域名,自动部署
root@iZuf65kw6tdqw5pext4gsdZ:/etc/letsencrypt# certbot
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Which names would you like to activate HTTPS for?
We recommend selecting either all domains, or all domains in a VirtualHost/server block.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: grafana.example.cn
2: mes.example.cn
3: sit.example.cn
4: admin-sit.example.cn
5: sit3.example.cn
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 3
Requesting a certificate for sit.example.cn
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/sit.example.cn/fullchain.pem
Key is saved at: /etc/letsencrypt/live/sit.example.cn/privkey.pem
This certificate expires on 2025-08-27.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.
Deploying certificate
Successfully deployed certificate for sit.example.cn to /etc/nginx/conf.d/psit.conf
Congratulations! You have successfully enabled HTTPS on https://sit.example.cn
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
* Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
* Donating to EFF: https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -