在Nginx上部署SSL证书可以实现HTTPS安全连接,以下是详细步骤:
获取SSL证书文件(通常包括:
确保Nginx已安装且支持SSL(检查nginx -V
输出中是否有--with-http_ssl_module
)
将证书文件上传到服务器,推荐目录:
/etc/nginx/ssl/
包含:
- yourdomain.crt
(或.pem) - 主证书文件
- yourdomain.key
- 私钥文件
- (可选) ca-bundle.crt
- CA证书链文件
编辑Nginx配置文件(通常在/etc/nginx/sites-available/yourdomain.conf
):
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# 证书路径
ssl_certificate /etc/nginx/ssl/yourdomain.crt;
ssl_certificate_key /etc/nginx/ssl/yourdomain.key;
# (如果使用CA证书链)
# ssl_trusted_certificate /etc/nginx/ssl/ca-bundle.crt;
# 安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
# 其他配置...
location / {
root /var/www/html;
index index.html;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
# 测试配置是否正确
sudo nginx -t
# 重启Nginx使配置生效
sudo systemctl restart nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
sudo openssl dhparam -out /etc/nginx/dhparam.pem 2048
然后在配置中添加:
ssl_dhparam /etc/nginx/dhparam.pem;
使用在线工具检查:
命令行验证:
openssl s_client -connect yourdomain.com:443 -servername yourdomain.com
openssl x509 -noout -modulus -in cert.crt | openssl md5
通过以上步骤,您应该可以成功在Nginx上部署SSL证书并启用HTTPS安全连接。