Nginx 以高性能、低資源佔用佔據全球 Web 服務器市場主導地位。但默認配置存在多個安全隱患,本文梳理 10 大常見陷阱並給出具體修復配置,助你構建生產級安全的 Nginx 服務。
if 指令 (If Is Evil)if 屬於 rewrite 模塊,僅應在 location 中配合 rewrite/return 使用。在非 rewrite 指令中使用會導致不可預期行為 (配置合併邏輯缺陷)。
# ❌ 錯誤示例
location / {
if ($arg_id = 1) { proxy_pass https://backend; }
}
# ✅ 正確:使用 map 或 try_files
map $arg_id $backend {
1 https://backend1;
default https://backend2;
}
location / { proxy_pass $backend; }
location ~ \.php$ 會匹配 test.php.jpg、test.php%00.jpg 等偽裝文件,導致任意代碼執行。
try_files $uri =404; 確保文件物理存在才傳遞給 FastCGI。php.ini 設置 cgi.fix_pathinfo=0,禁止路徑信息修復攻擊。location ~ ^.+\.php$ 或雙重保險 location ~* \.php(/|$)。location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
autoindex 目錄瀏覽location / {
autoindex off; # 默認 off,顯式聲明防止繼承開啟
}
SSI 若被利用可導致文件包含、命令執行。
location / {
ssi off;
}
錯誤頁面、HTTP Header 默認攜帶版本號,助力攻擊者鎖定漏洞。
server_tokens off; # http, server, location 任意層級生效
client_body_buffer_size 1K; client_header_buffer_size 1k; client_max_body_size 1m; # 根據業務調整,如文件上傳需放大 large_client_header_buffers 2 1k;
client_body_timeout 10s; client_header_timeout 10s; keepalive_timeout 5 5; # header keepalive 超時 5s send_timeout 10s;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; # 限制請求頻率
limit_conn_zone $binary_remote_addr zone=addr:10m; # 限制並發連接
server {
limit_conn addr 20; # 單 IP 最大 20 並發連接
limit_req zone=one burst=20 nodelay; # 突發允許 20,超過延遲
}
Basic Auth 傳輸 Base64 編碼明文,極易竊聽。若必須用:
auth_basic_user_file 配合 htpasswd -c -B 生成 bcrypt 密碼 (而非 crypt/MD5)。yum update nginx/apt upgrade nginx) 獲取回港修補版本。server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
server_tokens off;
autoindex off;
ssi off;
client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 10m;
large_client_header_buffers 2 1k;
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 5 5;
send_timeout 10s;
limit_conn addr 20;
limit_req zone=one burst=20 nodelay;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_intercept_errors on;
}
location ~ /\.(git|svn|env|htaccess) {
deny all;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
Nginx 安全不僅是配置幾個參數,而是最小權限原則、纏繞防禦、持續更新的系統工程。從 if 陷阱到 PHP 處理器加固,從緩衝區限制到連接頻率控制,每一項都在縮小攻擊面。定期掃描、審計配置、訂閱安全公告,才能讓 Nginx 在高併發下穩健運行。