如何在Ubuntu上使用Let’s Encrypt SSL
Let’s Encrypt是由Mozilla、EFF等组织发起的免费SSL证书提供商,旨在为网站提供安全加密服务。以下是在Ubuntu服务器上使用Certbot工具获取、配置及管理Let’s Encrypt SSL证书的全流程指南。
一、前期准备
- 域名解析:确保拥有已备案的域名,并将域名A记录解析至服务器IP(如
www.example.com指向123.45.67.89)。 - 安装Web服务器:Ubuntu系统需提前安装Nginx或Apache(以Nginx为例,可通过
sudo apt install nginx安装)。 - 开放端口:通过安全组或防火墙开放80端口(HTTP验证)和443端口(HTTPS服务)。
二、安装Certbot客户端
Certbot是Let’s Encrypt官方推荐的自动化工具,支持Nginx/Apache集成。根据Web服务器类型选择安装命令:
- Nginx用户(推荐):
sudo apt update sudo apt install certbot python3-certbot-nginx - Apache用户:
sudo apt install certbot python3-certbot-apache
安装完成后,Certbot会自动配置与Web服务器的集成。
三、获取SSL证书
1. 自动配置(推荐)
若使用Nginx或Apache,可直接运行以下命令,Certbot会自动完成证书申请、Web服务器配置及验证:
# 单域名(同时包含www和非www)
sudo certbot --nginx -d example.com -d www.example.com
# 或Apache用户
sudo certbot --apache -d example.com -d www.example.com
运行后,Certbot会提示输入邮箱(用于重要通知)并同意服务条款,完成后会显示证书保存路径及配置结果。
2. 手动验证(Standalone模式)
若未使用Nginx/Apache,或需自定义配置,可使用standalone模式(需临时停止Web服务器):
# 停止Nginx(避免端口冲突)
sudo systemctl stop nginx
# 申请证书
sudo certbot certonly --standalone -d example.com -d www.example.com
# 启动Nginx
sudo systemctl start nginx
证书会保存至/etc/letsencrypt/live/example.com/目录。
3. 泛域名证书(DNS验证)
若需支持*.example.com等泛域名,需使用DNS验证(手动添加TXT记录):
sudo certbot certonly --manual --preferred-challenges dns -d *.example.com -d example.com
运行后会提示在DNS服务商处添加_acme-challenge.example.com的TXT记录(值为命令输出的字符串),验证通过后证书自动生成。
四、配置Web服务器
1. Nginx自动配置
使用--nginx参数时,Certbot会自动修改Nginx配置文件(位于/etc/nginx/sites-available/),添加以下SSL配置:
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# 其他配置(如root、index等)
}
无需手动修改,直接重启Nginx即可生效。
2. 手动配置(可选)
若未使用自动配置,需手动编辑Nginx配置文件,添加SSL参数:
sudo nano /etc/nginx/sites-available/example.com
在server块中添加:
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
保存后测试配置并重启Nginx:
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx # 重启服务
五、自动续期
Let’s Encrypt证书有效期为90天,需定期续期。Certbot提供自动续期功能,可通过以下步骤配置:
1. 测试续期流程
sudo certbot renew --dry-run
若输出“Congratulations, all renewals succeeded”,说明续期流程正常。
2. 添加定时任务
编辑crontab文件,设置每天凌晨3点自动检查并续期:
sudo crontab -e
添加以下内容(Nginx用户需添加--post-hook重启服务):
0 3 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
此任务会自动执行续期,并在完成后重启Nginx加载新证书。
六、验证配置
- 浏览器访问:输入
https://example.com,确认地址栏显示绿色锁形图标(表示HTTPS加密生效)。 - 检查证书状态:通过浏览器开发者工具(F12→Security)查看证书有效期及颁发机构。
- 命令行验证:使用OpenSSL命令检查证书详情:
查看“Validity”字段确认有效期。openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem -noout -text
常见问题解决
- 端口占用:确保80/443端口未被其他程序(如Apache、MySQL)占用,可通过
sudo netstat -tulnp | grep ':80'检查。 - 验证失败:检查域名解析是否生效(使用
ping example.com确认IP正确),或DNS缓存是否更新(等待10-15分钟)。 - 证书续订失败:查看Certbot日志(
/var/log/letsencrypt/letsencrypt.log)定位错误原因,常见原因为端口占用或域名解析变更。