在开始配置之前,请确保您已经准备好以下内容: 1. 有效的SSL证书(包括.crt或.pem文件和.key文件) 2. 已安装Nginx并正常运行HTTP服务 3. 服务器防火墙已开放443端口
将您的证书文件上传到服务器,通常建议放在/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/
编辑您的Nginx站点配置文件(通常在/etc/nginx/sites-available/your_site
):
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/nginx/ssl/your_domain.crt;
ssl_certificate_key /etc/nginx/ssl/your_domain.key;
# 提高安全性配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
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';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
# 其他配置...
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
sudo nginx -t # 测试配置是否正确
sudo systemctl restart nginx # 重启Nginx服务
在SSL配置块中添加:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
确保您的证书支持OCSP Stapling,并添加:
ssl_trusted_certificate /etc/nginx/ssl/your_domain_chain.crt;
ssl_stapling on;
ssl_stapling_verify on;
生成DH参数文件:
sudo openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048
然后在Nginx配置中添加:
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
如果您使用的是Let's Encrypt证书,可以使用certbot自动续期:
sudo apt-get install certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install certbot python3-certbot-nginx # CentOS/RHEL
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
sudo certbot renew --dry-run
配置完成后,可以使用以下工具验证您的HTTPS配置:
- SSL Labs测试
- 命令行工具:openssl s_client -connect yourdomain.com:443 -servername yourdomain.com
证书链不完整:
cat intermediate.crt >> your_domain.crt
合并证书私钥不匹配:
openssl x509 -noout -modulus -in your_domain.crt | openssl md5
openssl rsa -noout -modulus -in your_domain.key | openssl md5
Nginx无法启动:
tail -f /var/log/nginx/error.log
sudo netstat -tulnp | grep 443
按照以上步骤配置后,您的网站应该能够通过HTTPS安全访问,并获得良好的安全评级。