Nginx+Certbot申请免费SSL证书教程

本教程将指导你如何使用 Certbot 在 Nginx 上申请免费的 Let's Encrypt SSL 证书,并配置 HTTPS 自动续期。

Nginx+Certbot申请免费SSL证书教程

1. 安装 Nginx 和 Certbot

1.1 安装 Nginx

如果你的服务器还没有安装 Nginx,可以使用以下命令安装:

Ubuntu/Debian:

sudo apt update
sudo apt install nginx -y

CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install nginx -y

安装完成后,启动 Nginx 并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

检查 Nginx 是否运行:

systemctl status nginx

1.2 安装 Certbot

Certbot 是 Let’s Encrypt 官方推荐的自动化 SSL 证书管理工具。

Ubuntu/Debian:

sudo apt install certbot python3-certbot-nginx -y

CentOS/RHEL:

sudo yum install certbot python3-certbot-nginx -y

安装完成后,检查 Certbot 是否正确安装:

certbot --version

2. 申请 SSL 证书

2.1 申请证书

使用 Certbot 申请 SSL 证书时,需要确保你的域名已经解析到服务器的 IP 地址。

运行以下命令:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

将 yourdomain.com 替换为你的实际域名。

2.2 证书申请过程

Certbot 运行后会:

自动检测 Nginx 配置并验证域名的所有权。

自动生成 SSL 证书并更新 Nginx 配置以启用 HTTPS。

提示你是否重定向 HTTP 到 HTTPS,建议选择 "2: Redirect",以强制所有流量通过 HTTPS。

如果成功,你会看到如下提示:

Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/yourdomain.com/fullchain.pem

这说明 SSL 证书已成功安装并生效。

3. 配置 Nginx 以启用 HTTPS

如果 Certbot 没有自动修改你的 Nginx 配置,你需要手动编辑 Nginx 配置文件。

sudo nano /etc/nginx/sites-available/default

或者:

sudo nano /etc/nginx/conf.d/yourdomain.com.conf

确保 Nginx 配置如下:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}

保存并退出后,测试 Nginx 配置:

sudo nginx -t

如果没有错误,则重新加载 Nginx:

sudo systemctl restart nginx

4. 设置自动续期

Let's Encrypt 证书的有效期为 90 天,建议配置自动续期。

测试自动续期:

sudo certbot renew --dry-run

如果没有报错,可以设置定期自动续期:

sudo crontab -e

添加以下内容:

0 3 * * * certbot renew --quiet && systemctl reload nginx

这将每天凌晨 3 点自动检查并更新证书,如果证书更新成功,会自动重新加载 Nginx。

5. 验证 SSL 配置

在浏览器中访问 https://yourdomain.com,检查 SSL 证书是否正确启用。

你还可以使用以下命令查看证书信息:

sudo openssl x509 -in /etc/letsencrypt/live/yourdomain.com/fullchain.pem -text -noout

6. 总结

至此,你已经成功使用 Certbot 为 Nginx 配置了免费的 Let's Encrypt SSL 证书,并启用了自动续期。你的网站现在可以安全地提供 HTTPS 访问。

如果遇到问题,可以使用以下命令检查 Nginx 错误日志:

sudo journalctl -u nginx --no-pager | tail -n 50

希望本教程对你有所帮助!

评论 添加
暂无评论,来聊两句?