如何在Ubuntu上使用Let’s Encrypt SSL
Let’s Encrypt是由Mozilla、EFF等组织发起的免费SSL证书提供商,旨在为网站提供安全加密服务。以下是在Ubuntu服务器上使用Certbot工具获取、配置及管理Let’s Encrypt SSL证书的全流程指南。
www.example.com指向123.45.67.89)。sudo apt install nginx安装)。Certbot是Let’s Encrypt官方推荐的自动化工具,支持Nginx/Apache集成。根据Web服务器类型选择安装命令:
sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo apt install certbot python3-certbot-apache
安装完成后,Certbot会自动配置与Web服务器的集成。
若使用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会提示输入邮箱(用于重要通知)并同意服务条款,完成后会显示证书保存路径及配置结果。
若未使用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/目录。
若需支持*.example.com等泛域名,需使用DNS验证(手动添加TXT记录):
sudo certbot certonly --manual --preferred-challenges dns -d *.example.com -d example.com
运行后会提示在DNS服务商处添加_acme-challenge.example.com的TXT记录(值为命令输出的字符串),验证通过后证书自动生成。
使用--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即可生效。
若未使用自动配置,需手动编辑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提供自动续期功能,可通过以下步骤配置:
sudo certbot renew --dry-run
若输出“Congratulations, all renewals succeeded”,说明续期流程正常。
编辑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加密生效)。openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem -noout -text
查看“Validity”字段确认有效期。sudo netstat -tulnp | grep ':80'检查。ping example.com确认IP正确),或DNS缓存是否更新(等待10-15分钟)。/var/log/letsencrypt/letsencrypt.log)定位错误原因,常见原因为端口占用或域名解析变更。