要在Nginx中启用HTTPS访问,您需要配置SSL模块。以下是完整的配置步骤:
nginx -V
查看输出中是否包含--with-http_ssl_module
。如果没有,您需要重新编译Nginx并添加SSL模块。
将您的证书文件(通常为.crt或.pem)和私钥文件(.key)上传到服务器,建议存放在/etc/nginx/ssl/
目录下:
/etc/nginx/ssl/
├── yourdomain.crt
├── yourdomain.key
└── ca_bundle.crt # 如果需要证书链
编辑Nginx配置文件(通常在/etc/nginx/sites-available/yourdomain.conf
或/etc/nginx/conf.d/default.conf
):
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
# SSL证书配置
ssl_certificate /etc/nginx/ssl/yourdomain.crt;
ssl_certificate_key /etc/nginx/ssl/yourdomain.key;
# 如果需要证书链
ssl_trusted_certificate /etc/nginx/ssl/ca_bundle.crt;
# 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_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 启用HSTS
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 其他配置
root /var/www/yourdomain.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# 将HTTP重定向到HTTPS
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
# 测试配置是否正确
nginx -t
# 如果测试通过,重启Nginx
systemctl restart nginx
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# 生成DH参数(需要几分钟)
openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048
然后在Nginx配置中添加:
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
在listen指令中添加http2:
listen 443 ssl http2;
SSL证书不被信任:
openssl verify -CAfile ca_bundle.crt yourdomain.crt
验证证书Nginx启动失败:
tail -f /var/log/nginx/error.log
混合内容警告:
证书过期:
如果您没有商业SSL证书,可以使用Certbot获取免费的Let's Encrypt证书:
# 安装Certbot
sudo apt 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安全访问了。