给网站配置 HTTPS 已经是标配了,但很多人配完能用就算,没有充分考虑到安全性和性能。本文记录一些 Nginx TLS 配置的最佳实践。

1. 证书申请

推荐用 Let’s Encrypt,免费、自动化、受信任。

apt install -y certbot
certbot certonly --standalone -d example.com

证书路径通常在 /etc/letsencrypt/live/example.com/。

2. 最小化 TLS 协议

2026 年了,TLS 1.0 和 1.1 应该彻底淘汰:

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

3. 会话缓存

启用会话缓存和票证能减少握手开销:

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

4. OCSP Stapling

启用 OCSP Stapling 让客户端不需要单独去查询证书状态,加快握手:

ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 8.8.8.8 valid=300s;
resolver_timeout 5s;

5. HTTP 强制跳转 HTTPS

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

6. HSTS 头

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;

注意:HSTS 一旦设置,浏览器会强制走 HTTPS,如果你证书过期了网站就完全访问不了。先用短 max-age 测试。

7. 安全头

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

8. 隐藏版本号

server_tokens off;

9. HTTP/2

listen 443 ssl http2;

HTTP/2 多路复用能显著提升页面加载速度。

10. 证书自动续期

Let’s Encrypt 证书 90 天过期,certbot 装好后会自带 systemd timer:

systemctl status certbot.timer

测试续期:

certbot renew --dry-run

完整示例

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 HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
}

把这些配置项都加上,网站的 TLS 评分上 SSL Labs 应该能拿到 A+。