TLS 1.3 是目前最安全的传输层协议版本,相比 TLS 1.2 有显著的性能和安全优势。本文介绍如何在 Nginx 中正确配置 TLS 1.3,并提供经过验证的配置示例。
TLS 1.3 的核心优势#
TLS 1.3 相比 TLS 1.2 有以下关键改进:
- 握手简化:从 2-RTT 降至 1-RTT(0-RTT 可选),连接建立更快
- 移除不安全算法:仅保留 AEAD 加密套件,禁用 CBC 模式和 RC4
- 前向安全性:强制使用 ECDHE 密钥交换,始终支持 PFS
- 抗重放攻击:0-RTT 模式有重放保护机制
基础配置#
以下是 Nginx TLS 1.3 的基础配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
server {
listen 443 ssl http2;
server_name example.com;
# 证书配置
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
# TLS 协议版本(推荐仅启用 TLS 1.3,如需兼容可保留 TLS 1.2)
ssl_protocols TLSv1.3;
# 加密套件(TLS 1.3 只需配置服务器端套件)
# 建议按优先级排序:AES-256 > ChaCha20 > AES-128
ssl_prefer_server_ciphers on;
# TLS 1.3 加密套件(必须)
ssl_conf_command Ciphersuites TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256;
# TLS 1.2 加密套件(如需兼容)
ssl_conf_command CipherSuites ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
# HSTS(强制 HTTPS)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# Session 缓存
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
location / {
root /var/www/html;
index index.html;
}
}
|
配置验证#
配置完成后,使用以下命令验证:
1. 检查 Nginx 配置语法#
输出示例:
1
2
|
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
|
2. 使用 s_client 测试 TLS 1.3 连接#
1
|
openssl s_client -connect example.com:443 -tls1_3
|
关键输出应包含:
1
2
3
|
SSL handshake has read 2671 bytes and written 3408 bytes
Protocol : TLSv1.3
Cipher : TLS_AES_256_GCM_SHA384
|
3. 查看支持的 TLS 版本#
1
|
openssl s_client -connect example.com:443 </dev/null 2>/dev/null | grep -E "Protocol|Cipher"
|
4. 测试加密套件优先级#
1
|
openssl s_client -connect example.com:443 -tls1_3 -cipher 'TLS_AES_256_GCM_SHA384' </dev/null 2>/dev/null
|
5. 使用 testssl.sh 进行全面检测(可选)#
1
|
testssl --fast example.com
|
TLS 1.3 高级配置#
启用 0-RTT 加速#
TLS 1.3 支持 0-RTT 模式,首次连接后后续请求可实现零延迟:
⚠️ 注意:0-RTT 存在重放攻击风险,仅在对性能要求极高且风险可控的场景使用。
禁用 TLS 1.2 强制兼容#
如无旧客户端兼容需求,可仅启用 TLS 1.3:
配置 CRL 和 OCSP#
1
2
|
ssl_crl /path/to/crl.pem;
ssl_trusted_certificate /path-to/ca-bundle.crt;
|
安全加固建议#
- 定期更新 OpenSSL 和 Nginx:确保使用最新版本,获取安全修复
- 使用现代证书:优先使用 ECDSA 或 RSA-2048 以上密钥
- 启用 HSTS:强制浏览器使用 HTTPS
- 配置安全头:除 HSTS 外,添加 CSP、X-Frame-Options 等
- 监控证书过期:使用自动化工具监控证书有效期
常见问题#
Q: Nginx 报错 “ssl_conf_command Ciphersuites” 怎么办?
A: 确保 OpenSSL 版本支持 TLS 1.3(OpenSSL 1.1.1+)。检查命令:openssl version
Q: TLS 1.3 握手失败?
A: 检查防火墙是否开放 443 端口,确认客户端浏览器支持 TLS 1.3
Q: 如何查看当前 TLS 配置效果?
A: 使用 Chrome 开发者工具 → Security 标签,或使用 ssllabs.com 进行检测
参考来源#