在Nginx服务器上安装SSL证书的步骤如下:
首先,确保你已经从证书颁发机构(CA)获取了以下文件:
- 证书文件(.crt或.pem):通常是 your_domain.crt
或 your_domain.pem
- 私钥文件(.key):通常是 your_domain.key
- 中间证书(可选):有时CA会提供中间证书文件(如 intermediate.crt
)
如果是Let's Encrypt证书,证书通常位于 /etc/letsencrypt/live/your_domain/
目录下,包含:
- fullchain.pem
(证书+中间证书)
- privkey.pem
(私钥)
将证书文件和私钥上传到Nginx的配置目录(例如 /etc/nginx/ssl/
):
sudo mkdir -p /etc/nginx/ssl
sudo cp your_domain.crt /etc/nginx/ssl/
sudo cp your_domain.key /etc/nginx/ssl/
确保私钥权限严格(仅root可读):
sudo chmod 600 /etc/nginx/ssl/your_domain.key
编辑Nginx的站点配置文件(通常在 /etc/nginx/sites-available/your_site
或 /etc/nginx/conf.d/your_site.conf
):
server {
listen 443 ssl;
server_name your_domain.com;
# SSL证书路径
ssl_certificate /etc/nginx/ssl/your_domain.crt;
ssl_certificate_key /etc/nginx/ssl/your_domain.key;
# 如果使用中间证书,合并到证书文件或单独指定
# ssl_trusted_certificate /etc/nginx/ssl/intermediate.crt;
# 启用强加密协议
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
# 其他配置(如root、index等)
root /var/www/html;
index index.html;
}
添加以下配置到80端口的server块:
server {
listen 80;
server_name your_domain.com;
return 301 https://$host$request_uri;
}
检查配置语法:
sudo nginx -t
若无错误,重载Nginx:
sudo systemctl reload nginx
使用工具检查是否生效:
- 访问 https://your_domain.com
确认浏览器锁标志。
- 使用在线工具如 SSL Labs 测试配置安全性。
证书链不完整
确保证书文件包含中间证书(合并到 .crt
文件)。
私钥不匹配
检查私钥是否与证书匹配:
openssl x509 -noout -modulus -in /etc/nginx/ssl/your_domain.crt | openssl md5
openssl rsa -noout -modulus -in /etc/nginx/ssl/your_domain.key | openssl md5
两次输出的哈希值必须一致。
防火墙阻止443端口
确保防火墙放行HTTPS流量:
sudo ufw allow 443/tcp
如果使用Let's Encrypt,安装Certbot自动续签:
sudo apt install certbot python3-certbot-nginx # Debian/Ubuntu
sudo certbot --nginx -d your_domain.com
证书会自动更新并配置Nginx。