如何通过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
相关产品推荐
相关产品推荐

