Nginx與安全相關的幾個配置
隨著網絡威脅的不斷演變,保護網站免受潛在攻擊變得尤為重要。Nginx,作為一款強大而靈活的 web 服務器和反向代理服務器,提供了一系列的安全相關參數,可以幫助加固網站安全性。在這篇文章中,我們將介紹一些基于 Nginx 的安全參數配置,以確保您的網站更加健壯和安全。
1. 隱藏服務器版本信息
為了降低攻擊者獲取系統信息的可能性,我們可以通過設置 server_tokens 來隱藏服務器版本信息。在 Nginx 配置中添加如下設置:
server_tokens off;
2. SSL/TLS 安全配置
對于使用 HTTPS 的網站,SSL/TLS 配置至關重要。確保使用強密碼和安全的協議版本。示例配置如下:
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384';
ssl_prefer_server_ciphers off;
3. 防止點擊劫持
通過配置 X-Frame-Options 可以防止網頁被嵌套在 <frame>、<iframe> 或 <object> 中,從而防止點擊劫持攻擊。
add_header X-Frame-Options "SAMEORIGIN";
4. 防止跨站腳本攻擊 (XSS)
使用 X-XSS-Protection 頭啟用瀏覽器內置的 XSS 過濾器。
add_header X-XSS-Protection "1; mode=block";
5. 防止 MIME 類型嗅探
通過設置 X-Content-Type-Options 防止瀏覽器執行某些文件類型的 MIME 類型嗅探。
add_header X-Content-Type-Options "nosniff";
6. 限制請求大小和超時
為了防止惡意請求或慢速攻擊,設置請求頭大小和請求超時時間。
client_max_body_size 10M;
client_body_timeout 12s;
7. 防止瀏覽器緩存敏感信息
這組配置禁止瀏覽器對響應進行緩存,確保每次請求都會向服務器驗證資源的有效性。
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Expires "0";
8. 設置安全的 Cookie
通過設置安全的 Cookie,僅允許通過 HTTPS 傳輸,且不可通過 JavaScript 訪問,提高對會話劫持和 XSS 攻擊的防護。
add_header Set-Cookie "cookie_name=value; Path=/; Secure; HttpOnly";
9. 處理跨域請求
以上配置用于處理跨域請求,確保安全地允許指定域的跨域請求,并處理預檢請求(OPTIONS 請求)。
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://your-allowed-domain.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' 'https://your-allowed-domain.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' 'https://your-allowed-domain.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
以上是一些基本的 Nginx 安全配置示例,但請注意,這只是一個起點。根據您的實際需求和安全最佳實踐,可以進一步調整和配置。請務必仔細查閱 Nginx 文檔以獲取最新的安全建議,并定期審查和更新您的安全策略,以確保網站的持續安全性。