要在Nginx中配置SSL证书,您需要遵循以下步骤:
首先,您需要获取SSL证书,可以通过以下方式之一: - 从证书颁发机构(CA)购买(如DigiCert, GlobalSign等) - 使用Let's Encrypt免费证书 - 生成自签名证书(仅用于测试)
通常您会获得以下文件:
- 域名证书(如domain.crt
或domain.pem
)
- 私钥文件(如domain.key
)
- 中间证书/CA证书链(如intermediate.crt
)
在Nginx配置文件中(通常在/etc/nginx/sites-available/your-site
),添加SSL配置:
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /path/to/your_domain.crt;
ssl_certificate_key /path/to/your_private.key;
# 配置SSL协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
# 其他配置...
location / {
root /var/www/html;
index index.html;
}
}
如果您的CA提供了中间证书,需要将它们合并:
cat your_domain.crt intermediate.crt > combined.crt
然后在Nginx配置中使用合并后的文件:
ssl_certificate /path/to/combined.crt;
添加以下配置将所有HTTP流量重定向到HTTPS:
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
# 启用会话缓存以提高性能
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 启用OCSP Stapling提高验证速度
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# 启用HSTS(HTTP严格传输安全)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
测试配置是否正确:
sudo nginx -t
重启Nginx使配置生效:
sudo systemctl restart nginx
使用以下工具验证您的SSL配置:
- SSL Labs测试工具
- 命令行工具:
bash
openssl s_client -connect yourdomain.com:443 -servername yourdomain.com
如果您使用Let's Encrypt,可以使用Certbot自动完成所有配置:
安装Certbot:
sudo apt install certbot python3-certbot-nginx
获取并安装证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
设置自动续订:
sudo certbot renew --dry-run
这样Certbot会自动配置Nginx并设置证书自动续订。
希望这个指南对您有所帮助!如有任何具体问题,请随时提问。