在Nginx反向代理配置中使用第三方SSL证书(如Let's Encrypt、DigiCert、GeoTrust等)可以确保客户端与服务器之间的通信安全加密。
获取SSL证书文件(通常包括):
.crt
或.pem
).key
)chain.crt
或bundle.crt
)确保Nginx已安装SSL模块(通常现代Nginx版本默认包含)
server {
listen 443 ssl;
server_name yourdomain.com;
# 证书文件路径
ssl_certificate /path/to/your_domain.crt;
ssl_certificate_key /path/to/your_domain.key;
# 中间证书链(如果需要)
ssl_trusted_certificate /path/to/chain.crt;
# SSL协议配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
# 其他反向代理配置
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
某些CA提供的证书需要将主证书和中间证书合并:
cat your_domain.crt intermediate.crt > combined.crt
然后在Nginx配置中使用合并后的文件:
ssl_certificate /path/to/combined.crt;
# 启用OCSP Stapling提高性能
ssl_stapling on;
ssl_stapling_verify on;
# 设置会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# DH参数(生成命令:openssl dhparam -out /etc/nginx/dhparam.pem 2048)
ssl_dhparam /etc/nginx/dhparam.pem;
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
错误现象:浏览器显示"证书不受信任"或"证书链不完整"
解决方案: - 确保证书文件包含完整的证书链 - 使用在线工具(如SSL Labs测试)验证证书链
错误现象:Nginx启动失败,报错"SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch"
解决方案:
- 确保证书和私钥匹配
- 验证命令:openssl x509 -noout -modulus -in certificate.crt | openssl md5
和 openssl rsa -noout -modulus -in private.key | openssl md5
应该输出相同的哈希值
解决方案: - 更新ssl_protocols和ssl_ciphers配置 - 参考Mozilla SSL配置生成器获取最新推荐配置
使用Certbot自动获取和更新证书:
# 安装Certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书(Nginx插件模式)
sudo certbot --nginx -d yourdomain.com
# 测试自动续订
sudo certbot renew --dry-run
Certbot会自动修改Nginx配置并设置定时任务更新证书。
通过以上配置,您可以安全高效地在Nginx反向代理中使用第三方SSL证书。