插件窝 干货文章 Nginx怎么使用Let's Encrypt加密https

Nginx怎么使用Let's Encrypt加密https

Nginx 配置 yourdomain Certbot 996    来源:    2025-04-27

使用 Let's Encrypt 为 Nginx 配置 HTTPS 可以通过 Certbot 工具快速实现。以下是详细步骤:


1. 准备工作

  • 确保域名已解析到服务器IP
  • 服务器已安装 Nginx 并正常运行(sudo systemctl status nginx
  • 开放 80(HTTP)和 443(HTTPS)端口

2. 安装 Certbot

# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx

3. 获取 SSL 证书

方法一:自动配置(推荐)

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

Certbot 会自动: 1. 验证域名所有权 2. 获取证书 3. 修改 Nginx 配置启用 HTTPS 4. 设置自动续期

方法二:手动配置(高级用户)

# 仅获取证书(不修改配置)
sudo certbot certonly --nginx -d yourdomain.com

# 手动修改 Nginx 配置
sudo vim /etc/nginx/sites-available/yourdomain.conf

添加以下配置:

server {
    listen 443 ssl;
    server_name yourdomain.com;
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    # 其他配置...
}

4. 强制 HTTPS 跳转(可选)

在 Nginx 配置中添加 301 重定向:

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

5. 验证 Nginx 配置并重启

sudo nginx -t   # 测试配置
sudo systemctl reload nginx

6. 自动续期

Let's Encrypt 证书有效期为 90 天,设置自动续期:

# 测试续期命令
sudo certbot renew --dry-run

# 添加定时任务(每月执行)
sudo crontab -e

添加以下行:

0 0 1 * * /usr/bin/certbot renew --quiet

验证 HTTPS

访问 https://yourdomain.com,浏览器应显示绿色锁标志。可通过 SSL Labs 测试安全性。


常见问题

  1. 证书获取失败

    • 检查域名解析是否正确
    • 确保 80 端口未被占用(sudo lsof -i :80
  2. Nginx 配置错误

    • 使用 nginx -t 检查语法
    • 确保证书路径正确(路径中的 yourdomain.com 需替换为实际域名)
  3. 混合内容警告

    • 确保网页内所有资源(图片/JS/CSS)使用 https:// 链接

通过以上步骤,你的 Nginx 将获得免费的 Let's Encrypt HTTPS 证书,并自动维护续期。