用Let’s Encrypt给站点加HTTPS,核心就两步:装certbot,跑命令拿证书。不用花钱,证书90天过期,但配合cron自动续期基本不用管。
环境:Ubuntu 22.04,Nginx。其他Linux发行版大同小异,包管理器换一下就行。
1. 安装certbot
我用snap装,官方推荐方式,自动处理依赖和更新。
sudo apt update
sudo apt install snapd
sudo snap install core
sudo snap refresh core
sudo snap install --classic certbot
装完确认版本:
certbot --version
如果提示命令找不到,软链一下:
sudo ln -s /snap/bin/certbot /usr/bin/certbot
2. 申请证书
我习惯用Nginx插件模式,certbot自动修改Nginx配置、自动验证域名所有权。前提是域名已经解析到服务器IP,且80端口能访问。
sudo certbot --nginx -d example.com -d www.example.com
这里-d后面跟域名,多个域名空格隔开。certbot会检测Nginx配置,让你选是否强制HTTPS重定向,选2(Redirect)就行。
跑完输出类似:
Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/example.com/fullchain.pem
证书文件位置记一下,后面Nginx配置直接引用。
3. 手动配置Nginx(如果不想用–nginx插件)
有些场景不想让certbot改Nginx配置,比如已经自己配好了HTTPS。那就用certonly模式:
sudo certbot certonly --nginx -d example.com
或者用standalone模式(需要临时占用80或443端口,先停掉Nginx):
sudo systemctl stop nginx
sudo certbot certonly --standalone -d example.com
sudo systemctl start nginx
拿到证书后,在Nginx配置里手动指定:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
4. 自动续期
Let’s Encrypt证书有效期90天,certbot自带续期命令。先测试一下续期是否正常:
sudo certbot renew --dry-run
没报错就加到crontab里,每天跑两次(Let’s Encrypt建议)。编辑crontab:
sudo crontab -e
加一行:
0 0,12 * * * /usr/bin/certbot renew --quiet
–quiet表示成功不输出日志,失败才发邮件。cron执行结果会发到root邮箱,懒得看可以重定向到日志文件:
0 0,12 * * * /usr/bin/certbot renew --quiet >> /var/log/certbot-renew.log 2>&1
5. 常见问题
– 申请时报”DNS problem: NXDOMAIN”:域名没解析到当前服务器IP,检查DNS记录。
– 报”Too many certificates already issued”:Let’s Encrypt每周每域名限制20个证书,测试用staging环境:
sudo certbot --nginx -d example.com --staging
– 证书快过期但renew没反应:certbot只会在剩余30天内才真正续期,dry-run通过就不用管。
6. 服务器推荐
证书申请本身不依赖服务器厂商,但如果你需要一台稳定跑Nginx的机器,我目前用雨云,性价比确实可以,配置简单,续费也不涨价。之前用其他家动不动就限速,雨云带宽给得足,适合挂站或跑API。国内访问速度也不错,备案流程他们客服会指导。
7. 验证证书
部署完检查证书是否生效:
curl -I https://example.com
看返回头有没有HTTP/2 200。也可以用openssl查看证书有效期:
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates
输出类似:
notBefore=Jan 15 00:00:00 2025 GMT
notAfter=Apr 15 00:00:00 2025 GMT
到期前certbot会自动续,你只需保证cron在跑、80端口能访问验证文件。
提醒:不要手动复制证书文件到其他地方,certbot续期后会更新live目录下的软链接,你配置里直接引用live路径就行。
雨云是国内一家老牌云服务商,提供高性价比的云服务器和虚拟主机。我用它部署了好几个项目,速度和稳定性都不错。通过 https://www.rainyun.com/SAJA_ 注册可以领一张 5折优惠券,有需要的朋友可以看看。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



暂无评论内容