要在Nginx上配置SSL证书实现HTTPS访问,您需要完成以下步骤:
首先,您需要获取有效的SSL证书,可以选择:
# 安装Certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书(替换yourdomain.com)
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
编辑Nginx配置文件(通常在/etc/nginx/sites-available/yourdomain.com
):
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# SSL证书路径
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# SSL优化配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
# 其他配置...
root /var/www/yourdomain.com/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;
}
# 测试Nginx配置
sudo nginx -t
# 重启Nginx使配置生效
sudo systemctl restart nginx
Let's Encrypt证书每90天过期,设置自动续期:
# 测试续期
sudo certbot renew --dry-run
# 添加crontab任务自动续期
sudo crontab -e
添加以下行(每天检查并续期):
0 12 * * * /usr/bin/certbot renew --quiet
访问您的网站,确认: 1. 浏览器地址栏显示安全锁标志 2. 使用SSL Labs测试工具检查配置安全性
listen 443 ssl http2;
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header X-XSS-Protection "1; mode=block";
ssl_protocols
配置,禁用不安全的TLS 1.0/1.1如需进一步帮助,请提供具体的错误信息或配置细节。