Nginx安全保障體系構建指南
nginx.conf
)或server
塊中添加server_tokens off;
,禁止響應頭中暴露Nginx版本號;進一步可配合headers-more-nginx-module
模塊移除Server
頭部,徹底降低版本探測風險。limit_except
指令限制僅允許必要方法(如GET
、POST
),攔截PUT
、DELETE
等危險請求,示例:limit_except GET POST { deny all; }
。client_max_body_size
指令限制上傳文件大?。ㄈ?code>client_max_body_size 10M;),防止惡意用戶上傳超大文件耗盡服務器磁盤空間。allow
/deny
指令限制敏感路徑的IP訪問,例如僅允許內網IP訪問管理后臺:location /admin { allow 192.168.1.0/24; deny all; }
。htpasswd
工具創建認證文件(sudo htpasswd -c /etc/nginx/.htpasswd username
),在需要保護的路徑啟用HTTP Basic認證:location /private { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; }
。nginx
)運行Nginx進程(user nginx;
),并設置配置文件權限為640
(chmod 640 /etc/nginx/nginx.conf
),避免未授權用戶修改配置。certbot --nginx -d yourdomain.com
)獲取免費證書,或購買商業證書,配置ssl_certificate
(公鑰路徑)和ssl_certificate_key
(私鑰路徑),強制HTTP跳轉HTTPS。ECDHE-ECDSA-AES256-GCM-SHA384
),示例:ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers on;
。Strict-Transport-Security
頭部,強制瀏覽器僅通過HTTPS訪問,防止降級攻擊,示例:add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
。union select
、<script>
等關鍵詞的請求,示例:if ($args ~* "union.*select.*\(|<script.*>") { return 403; }
;同時添加X-XSS-Protection
(add_header X-XSS-Protection "1; mode=block";
)和X-Content-Type-Options
(add_header X-Content-Type-Options "nosniff";
)頭部,增強瀏覽器防護。X-Frame-Options
頭部限制頁面嵌入iframe,示例:add_header X-Frame-Options "SAMEORIGIN";
,防止攻擊者在網頁中插入惡意iframe誘導用戶點擊。limit_req_zone
定義共享內存區域(如limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
),在location
塊中應用limit_req
指令,限制單IP每秒請求數(如limit_req zone=mylimit burst=20;
),超出閾值的請求返回503狀態碼,防范DDoS和暴力破解。limit_conn_zone
限制單IP并發連接數(如limit_conn_zone $binary_remote_addr zone=addr:10m;
),在location
塊中應用limit_conn
指令(如limit_conn addr 10;
),防止過多連接耗盡服務器資源。access_log /var/log/nginx/access.log main;
)和錯誤日志(error_log /var/log/nginx/error.log warn;
),自定義log_format
記錄關鍵字段(如客戶端IP、請求時間、狀態碼、請求URI),便于后續審計。logrotate
工具),避免單個日志文件過大;通過ELK、Prometheus等工具實時監控日志,設置異常告警(如頻繁的404請求、503錯誤),及時發現攻擊行為。/var/log/nginx/error.log
),對多次登錄失敗的IP進行封禁(如maxretry = 3
,bantime = 3600
),防范暴力破解。apt list --upgradable | grep nginx
),及時升級到最新穩定版本,修復已知漏洞;編譯時禁用未使用的模塊(如--without-http_autoindex_module
),減少攻擊面。.crt
、.key
)存儲在加密目錄(如/etc/ssl/private/
),權限設置為600
;定期更新證書(如Let’s Encrypt證書有效期為90天),避免證書過期導致服務中斷。