首先需要获取SSL证书,可以使用Let's Encrypt免费证书或商业证书:
# 使用Let's Encrypt获取证书 (certbot)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# 启用会话恢复以减少计算开销
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 禁用SSLv3,推荐使用TLS协议
ssl_protocols TLSv1.2 TLSv1.3;
# 配置加密套件
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_prefer_server_ciphers on;
# HSTS (可选但推荐)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 其他配置...
location / {
root /var/www/html;
index index.html;
}
}
ssl_protocols TLSv1.2 TLSv1.3; # 禁用旧版协议
ssl_ecdh_curve secp384r1; # 使用更强的椭圆曲线
ssl_dhparam /etc/nginx/dhparam.pem; # 生成强DH参数: openssl dhparam -out /etc/nginx/dhparam.pem 4096
# 仅TLS 1.3的加密套件
ssl_ciphers 'TLS13+AESGCM+AES256:TLS13+CHACHA20:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
ssl_session_cache shared:SSL:50m;
ssl_session_timeout 1d;
ssl_session_tickets off; # 对于TLS 1.2及以下版本
ssl_early_data on;
设置cron任务自动续期Let's Encrypt证书:
# 编辑crontab
crontab -e
# 添加以下内容(每周检查续期)
0 0 * * 0 /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
配置完成后,使用以下工具检测配置安全性:
# 安装testssl.sh
git clone --depth 1 https://github.com/drwetter/testssl.sh.git
cd testssl.sh
./testssl.sh yourdomain.com
nginx
add_header Content-Security-Policy "upgrade-insecure-requests";
ssl_certificate
包含完整证书链cat
命令合并证书:
bash
cat domain.crt intermediate.crt > chained.crt
如需支持旧客户端,可以调整加密套件:
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
通过以上配置,您可以建立一个安全、高效的HTTPS服务,保障数据传输的安全性。