Nginx 配置 HTTPS 完整指南

为什么必须用 HTTPS

现在几乎所有网站都应该启用 HTTPS。不仅是安全考虑,还因为:

  • Chrome 等浏览器会将 HTTP 站点标记为「不安全」
  • HTTP/2 和 HTTP/3 都需要 TLS
  • 某些浏览器 API(如地理位置、Service Worker)要求 HTTPS

申请免费证书

使用 Let’s Encrypt(推荐)

# 安装 certbot
apt install certbot python3-certbot-nginx -y

# 自动配置 Nginx(推荐新手)
certbot --nginx -d yourdomain.com

# 或者只获取证书,手动配置
certbot certonly --nginx -d yourdomain.com

证书文件会存放在 /etc/letsencrypt/live/yourdomain.com/ 目录下。

手动申请

如果服务器不能直接访问 80 端口,可以用 DNS 验证:

certbot certonly --manual --preferred-challenges dns -d yourdomain.com

按照提示在 DNS 中添加 TXT 记录即可。

Nginx 配置

基础 HTTPS 配置

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

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

    # SSL 优化配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    root /var/www/yourdomain.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

HTTP 自动跳转

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

反向代理 + HTTPS

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

    ssl_certificate     /path/to/fullchain.pem;
    ssl_certificate_key /path/to/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

自动续期

Let’s Encrypt 证书有效期为 90 天,需要定期续期:

# 测试续期(不会真的续期)
certbot renew --dry-run

# 添加到 crontab(每周检查一次)
0 3 * * 1 certbot renew --quiet && systemctl reload nginx

常见问题

  1. 混合内容警告:页面中仍有 HTTP 资源,需要全部改为 HTTPS 或相对路径
  2. 证书链不完整:使用 fullchain.pem 而不是 cert.pem
  3. SSL 评分低:检查 SSL Labs 报告,关闭过旧的协议版本和弱加密套件

总结

HTTPS 配置其实不难,核心就是三步:申请证书 → 配置 Nginx → 设置自动续期。建议第一次操作时完整走一遍流程,后面就轻车熟路了。