HTTPS 已经成为现代网站的标配。本文记录了使用 Let's Encrypt 和 Nginx 配置 HTTPS 的完整过程。

安装 Certbot

Certbot 是 Let's Encrypt 官方推荐的证书管理工具:

sudo apt update
sudo apt install certbot python3-certbot-nginx

申请证书

使用 Nginx 插件可以自动完成证书申请和配置:

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

如果只想申请证书而不自动修改 Nginx 配置:

sudo certbot certonly --nginx -d example.com

Nginx 配置

一个推荐的 HTTPS 配置如下:

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 off;

    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
}

HTTP 到 HTTPS 的重定向

确保所有 HTTP 请求都被重定向到 HTTPS:

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

自动续期

Let's Encrypt 的证书有效期为 90 天,需要设置自动续期。Certbot 安装时通常会自动配置定时任务,可以通过以下命令测试:

sudo certbot renew --dry-run

如果没有自动配置,可以添加 crontab:

0 3 * * * certbot renew --quiet --post-hook "systemctl reload nginx"

安全响应头

建议添加以下安全响应头:

add_header X-Frame-Options        "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy        "no-referrer-when-downgrade" always;

配置完成后记得测试 Nginx 配置语法并重载:

sudo nginx -t
sudo systemctl reload nginx