You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过WAFv2规则限制特定域名访问API Gateway?

实现AWS WAFv2限制特定域名访问API Gateway的Terraform方案

你之前通过Terraform配置了基于IP限制的WAFv2规则,现在要改为限制特定域名(abcde.com、us1a.bcde.com)访问API Gateway,可通过匹配请求的Host请求头实现,具体方案如下:

核心思路

AWS WAFv2支持通过byte_match_statement或regex_match_statement检查HTTP请求头中的Host字段,以此识别请求来源的域名,进而配置允许/阻止动作。以下是完整的Terraform配置示例:

替换后的Terraform配置

resource "aws_wafv2_web_acl" "firewall" {
  name  = "firewall"
  scope = "REGIONAL"

  # 默认动作:允许所有请求,除非匹配到规则中的域名则阻止
  default_action {
    allow {}
  }

  rule {
    name     = "domain-blocklist"
    priority = 1

    # 匹配到目标域名时执行阻止动作
    action {
      block {}
    }

    statement {
      # 使用OR逻辑匹配多个域名
      or_statement {
        statements {
          # 匹配abcde.com
          byte_match_statement {
            field_to_match {
              single_header {
                name = "Host"
              }
            }
            positional_constraint = "EXACTLY"
            search_string         = "abcde.com"
            text_transformation {
              priority = 0
              type     = "LOWERCASE" # 统一转为小写,避免大小写匹配问题
            }
          }
        }

        statements {
          # 匹配us1a.bcde.com
          byte_match_statement {
            field_to_match {
              single_header {
                name = "Host"
              }
            }
            positional_constraint = "EXACTLY"
            search_string         = "us1a.bcde.com"
            text_transformation {
              priority = 0
              type     = "LOWERCASE"
            }
          }
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "BlockedDomain"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "AllowedRequests"
    sampled_requests_enabled   = true
  }
}

resource "aws_wafv2_web_acl_association" "this" {
  resource_arn = aws_api_gateway_stage.api_stage.arn
  web_acl_arn  = aws_wafv2_web_acl.firewall.arn
}

关键配置说明

  • 默认动作调整:将原来的block改为allow,确保未匹配到规则的请求能正常访问;规则动作设为block,拦截指定域名的请求。
  • Host头匹配:通过single_header指定检查Host字段,EXACTLY表示精确匹配域名;添加LOWERCASE转换避免大小写敏感问题。
  • 多域名匹配:使用or_statement包裹多个byte_match_statement,实现同时匹配多个目标域名。

可选优化:使用正则匹配泛域名

如果需要匹配*.bcde.com这类泛域名,可将byte_match_statement替换为regex_match_statement,示例如下:

statements {
  regex_match_statement {
    field_to_match {
      single_header {
        name = "Host"
      }
    }
    regex_string = "^.*\\.bcde\\.com$"
    text_transformation {
      priority = 0
      type     = "LOWERCASE"
    }
  }
}

内容的提问来源于stack exchange,提问作者Sayon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:10:37