Ubuntu Nginx配置HTTPS的關鍵注意事項
sudo certbot --nginx -d yourdomain.com
即可自動完成證書申請與Nginx配置。openssl req -x509 -nodes -days 365 -newkey rsa:2048
生成自簽名證書,但瀏覽器會提示“不安全”,需手動信任。.crt
/.pem
)和私鑰文件(.key
)路徑正確,避免權限問題(私鑰需設置為600
權限)。Let’s Encrypt證書路徑通常為/etc/letsencrypt/live/yourdomain.com/
。server
塊中添加return 301 https://$host$request_uri;
,將所有HTTP請求永久重定向至HTTPS,提升安全性與SEO效果。例如:server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
ssl_protocols TLSv1.2 TLSv1.3;
。ECDHE
(橢圓曲線迪菲-赫爾曼)系列算法,如ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
,兼顧安全性與性能。ssl_prefer_server_ciphers on;
,確保服務器優先選擇加密套件,提升前向保密性。sudo nginx -t
檢查語法錯誤,避免因配置錯誤導致服務無法啟動。sudo systemctl reload nginx
重載配置,無需中斷現有連接。/etc/nginx/nginx.conf
的http
塊中添加server_tokens off;
,避免響應頭中泄露Nginx版本,減少針對性攻擊。http
塊中添加限流配置(如limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
),防止DDoS或暴力破解。server
塊中添加以下頭部,提升安全性:
Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
:強制瀏覽器使用HTTPS(有效期2年);X-Frame-Options "DENY"
:防止頁面被嵌入iframe(防范點擊劫持)。/var/log/nginx/error.log
查看SSL配置錯誤(如證書過期、私鑰不匹配),通過access.log
監控HTTPS訪問情況。server
塊或使用301重定向(如將www
指向主域名);sudo ufw allow 443/tcp
)。sudo certbot renew --dry-run
測試自動續期功能,然后在crontab -e
中添加0 3 * * * /usr/bin/certbot renew --quiet
,每天凌晨3點自動嘗試續期。