萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MS SQL 資料庫

Nginx 防禦 SQL 注入:基於 URI 與 Query String 的 rewrite/return 規則實作

在 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。

擴充規則集 (參考 OWASP ModSecurity Core Rule Set)

# 疑似 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 ~* "(

⚠️ 生產環境建議:

  1. **首選應用層參數化查詢** 修根本,Nginx 規則僅為第二道防線。
  2. 規則過於激進會誤攔正常業務 (如搜尋關鍵字含 "select"、部落格內容含 "
copyright © 萬盛學電腦網 all rights reserved