Skip to content

🔒 SSL/TLS 配置

为什么需要 HTTPS?

HTTP 就像明信片——邮递员(网络中间人)能看到内容。HTTPS 就像密封信封——只有收件人能打开。现代网站不用 HTTPS,浏览器会直接显示"不安全"警告。

使用 Let's Encrypt 免费证书

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

# 自动获取证书并配置 Nginx
sudo certbot --nginx -d example.com -d www.example.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Requesting a certificate for example.com and www.example.com
Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/example.com/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/example.com/privkey.pem

# 设置自动续期(Let's Encrypt 证书 90 天过期)
sudo certbot renew --dry-run
Congratulations, all simulated renewals succeeded

# 确保自动续期定时任务存在
sudo systemctl list-timers | grep certbot

手动配置 HTTPS

nginx
server {
    listen 443 ssl http2;
    server_name example.com;

    # 证书路径
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # 安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;

    # 启用 HSTS(告诉浏览器只用 HTTPS 访问此站)
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;

    # OCSP Stapling(加速证书验证)
    ssl_stapling on;
    ssl_stapling_verify on;

    location / {
        root /var/www/html;
    }
}

# HTTP 自动跳转到 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

⚠️ 注意: ⚠️ HSTS 注意:启用 HSTS 后,浏览器会在max-age期间强制使用 HTTPS。如果证书出问题,用户将无法通过 HTTP 访问你的网站。新手先用较小的max-age(如 300 秒)测试。