在开始配置前,请确保您已经: 1. 拥有一个域名 2. 申请了SSL证书(可以从Let's Encrypt、阿里云、腾讯云等获取) 3. 已安装Nginx服务器
将您的证书文件上传到服务器,通常包括:
- 证书文件(如 domain.crt
或 domain.pem
)
- 私钥文件(如 domain.key
)
建议将这些文件放在 /etc/nginx/ssl/
目录下:
sudo mkdir -p /etc/nginx/ssl/
sudo chmod 700 /etc/nginx/ssl/
sudo cp domain.crt /etc/nginx/ssl/
sudo cp domain.key /etc/nginx/ssl/
编辑Nginx配置文件(通常在 /etc/nginx/sites-available/your-site
或 /etc/nginx/conf.d/default.conf
):
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
# SSL证书配置
ssl_certificate /etc/nginx/ssl/domain.crt;
ssl_certificate_key /etc/nginx/ssl/domain.key;
# SSL协议配置
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性能
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# 启用OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
# HSTS (可选)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# 其他配置...
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$server_name$request_uri;
}
# 检查配置语法是否正确
sudo nginx -t
# 重启Nginx使配置生效
sudo systemctl restart nginx
如果您使用Let's Encrypt证书,可以使用Certbot简化流程:
sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
sudo certbot renew --dry-run
https://yourdomain.com
检查是否正常工作证书不受信任:
cat intermediate.crt >> domain.crt
合并证书Nginx启动失败:
tail -f /var/log/nginx/error.log
混合内容警告:
旧版SSL协议不安全:
通过以上步骤,您应该能够成功配置Nginx使用SSL证书实现HTTPS访问。如需更高级的安全配置,可以考虑添加更多安全头部或启用更严格的加密算法。