在 Web 應用防火牆 (WAF) 層面攔截 SQL 注入特徵,可顯著降低資料庫風險。Nginx 透過 rewrite (匹配 URI) 與 if + $query_string (匹配查詢參數) 實作輕量級防禦,將可疑請求導向 404/403。
# 1. URI 中攜帶疑似 SQL 注入字元 (單引號、分號、尖括號等)
location / {
rewrite ^.*[;'<>].* /404.html break; # 僅匹配 URI 部分 (問號前)
}
# 2. Query String (問號後參數) 匹配需用 $query_string 變數
# 例:/plus/list.php?tid=19&mid=1124'
if ($query_string ~* ".*[;'<>].*") {
return 404; # 或 return 403; / rewrite /block.html;
}
rewrite **只匹配 URI** ($uri),**不包含查詢字串** ($query_string / $args)。$query_string 保留原始查詢字串 (未解碼),可直接正則匹配。~*:大小寫不敏感正則匹配;~ 區分大小寫。break:停止當前 location 後續 rewrite,內部跳轉;last 重新尋找 location。# 疑似 SQL 關鍵字 (需謹慎,易誤攔正常流量)
if ($query_string ~* "(union|select|insert|update|delete|drop|alter|create|exec|xp_|sp_|0x[0-9a-f]+)") {
return 403;
}
# 疑似 XSS 腳本標籤
if ($query_string ~* "(
⚠️ 生產環境建議: