在申请Nginx SSL证书前,需完成以下准备工作:
ping yourdomain.com验证);systemctl status nginx检查状态);Certbot是Let’s Encrypt官方推荐的自动化证书管理工具,需通过以下命令安装:
sudo apt update && sudo apt install certbot python3-certbot-nginx -y
安装完成后,可通过certbot --version验证安装是否成功。
若仅需为单个域名(如example.com)申请证书,可直接运行以下命令:
sudo certbot --nginx -d example.com -d www.example.com
-d:指定域名(可同时添加多个,如主域名+www子域名);--nginx:让Certbot自动修改Nginx配置文件,无需手动编辑。操作提示:
*.example.com)若需要为泛域名(如*.example.com)申请证书,需使用DNS验证(因HTTP验证无法覆盖泛域名):
sudo certbot certonly --manual --preferred-challenges dns-01 -d "*.example.com" -d "example.com"
--manual:手动验证模式;--preferred-challenges dns-01:指定DNS验证方式。操作提示:
_acme-challenge.example.com);通过以下命令查看已安装证书的详细信息(包括有效期、路径等):
sudo certbot certificates
输出示例:
Found the following certs:
Certificate Name: example.com
Domains: example.com www.example.com
Expiry Date: 2025-12-31 23:59:59 (VALID: 90 days)
Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem
Private Key Path: /etc/letsencrypt/live/example.com/privkey.pem
确认Domains包含你的目标域名,Expiry Date在有效期内。
修改Nginx配置后,需通过以下命令测试语法是否正确:
sudo nginx -t
若输出nginx: configuration file /etc/nginx/nginx.conf syntax is ok,则表示配置正确。
测试通过后,重启Nginx使配置生效:
sudo systemctl restart nginx
Let’s Encrypt证书有效期为90天,需定期续期以避免服务中断。Certbot支持自动续期,无需手动操作:
运行以下命令模拟续期过程(无实际修改):
sudo certbot renew --dry-run
若输出Congratulations, all renewals succeeded,则表示自动续期配置正常。
编辑crontab文件,设置每天凌晨3点自动续期(续期成功后自动重启Nginx):
crontab -e
添加以下内容:
0 3 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
保存并退出,定时任务将自动生效。
nslookup yourdomain.com),开放80端口(sudo ufw allow 80)。sudo nginx -t定位错误,修改对应配置文件(如/etc/nginx/sites-available/yourdomain.conf)。sudo timedatectl set-ntp true),检查DNS记录是否已生效。通过以上步骤,即可在Ubuntu服务器上为Nginx成功申请并配置Let’s Encrypt免费SSL证书,实现网站的HTTPS加密访问。