HTTPS是保障网站数据传输安全的关键技术,本教程将详细介绍如何在Nginx服务器上配置HTTPS。
在配置HTTPS之前,您需要获取SSL证书。有以下几种方式:
Let's Encrypt:最流行的免费证书颁发机构
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Cloudflare:提供免费SSL证书(边缘证书)
将以下配置添加到您的Nginx站点配置文件中(通常在/etc/nginx/sites-available/yourdomain.com
):
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
# 启用SSL会话缓存以提高性能
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 安全配置
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';
# 启用HSTS
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 其他配置...
location / {
root /var/www/html;
index index.html index.htm;
}
}
为了确保所有流量都通过HTTPS,您应该将HTTP请求重定向到HTTPS:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
提高SSL验证性能和安全性的技术:
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
添加额外的安全头部:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
ssl_session_tickets on;
ssl_session_ticket_key /path/to/ticket.key;
listen 443 ssl http2;
测试Nginx配置:
sudo nginx -t
重新加载Nginx:
sudo systemctl reload nginx
使用在线工具验证配置:
对于Let's Encrypt证书(90天有效期),设置自动续订:
sudo crontab -e
添加以下行(每周检查并续订):
0 0 * * 0 certbot renew --quiet --post-hook "systemctl reload nginx"
证书链不完整:
ssl_certificate
包含中间证书cat certificate.crt intermediate.crt > combined.crt
合并证书混合内容警告:
TLS协议不匹配:
ssl_protocols
配置,确保客户端和服务器支持相同的协议证书过期:
通过以上配置,您的网站将获得A+级别的SSL安全评级,确保用户数据在传输过程中的安全性。