# 安装 certbot
sudo apt-get install certbot python3-certbot-nginx
# 获取证书并自动配置 Nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
如果你已有证书文件,通常包括:
- 证书文件(如 yourdomain.crt
或 yourdomain.pem
)
- 私钥文件(如 yourdomain.key
)
编辑 Nginx 配置文件(通常在 /etc/nginx/sites-available/yourdomain.conf
):
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# SSL 证书配置
ssl_certificate /path/to/yourdomain.crt;
ssl_certificate_key /path/to/yourdomain.key;
# 启用 SSL 会话缓存以提高性能
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 推荐的安全协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
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_prefer_server_ciphers on;
# 启用 HSTS (可选但推荐)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 其他配置...
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;
}
# 测试配置是否正确
sudo nginx -t
# 重新加载 Nginx 使配置生效
sudo systemctl reload nginx
Let's Encrypt 证书有效期为 90 天,设置自动续订:
# 测试续订
sudo certbot renew --dry-run
# 设置自动续订(certbot 默认已设置)
# 可以通过以下命令查看定时任务
sudo systemctl list-timers | grep certbot
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;
listen 443 ssl http2;
# 禁用不安全的内容类型
add_header X-Content-Type-Options nosniff;
# 防止点击劫持
add_header X-Frame-Options SAMEORIGIN;
# XSS 保护
add_header X-XSS-Protection "1; mode=block";
使用以下工具验证你的 HTTPS 配置: - SSL Labs SSL Test - Security Headers
ssl_protocols
和 ssl_ciphers
配置通过以上步骤,你应该能够成功为你的网站配置 HTTPS。如需进一步优化,可以考虑使用更高级的 TLS 配置或 CDN 服务来增强安全性和性能。