Terraform aws_wafv2_web_acl正则匹配多Header场景失效如何修复?
问题描述
我有一段Terraform的aws_wafv2_web_acl配置代码:
resource "aws_wafv2_web_acl" "main" { name = "main" description = "main" scope = "REGIONAL" default_action { allow {} } rule { name = "example" priority = 1 action { count {} } statement { not_statement { statement { regex_match_statement { regex_string = "^.*\\..+\\.example\\.com$" field_to_match { single_header { name = "host" } } text_transformation { priority = 0 type = "NONE" } } } } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "main" sampled_requests_enabled = true } } }
我的需求是统计所有不匹配以下域名的请求:
- api.stg.sample.example.com
- stg.sample.example.com
- admin.stg.sample.example.com
当前代码在仅Host头匹配正则时运行正常:符合要求的请求不会被统计(表现符合预期),例如:
httpRequest.headers.0.name host
httpRequest.headers.0.value api.stg.sample.example.com
但当请求包含多个匹配正则的Header时,代码失效:符合要求的请求被错误统计(不符合预期),例如:
httpRequest.headers.0.name host
httpRequest.headers.0.value api.stg.sample.example.com
httpRequest.headers.10.name referer
httpRequest.headers.10.value https://stg.sample.example.com
甚至测试简单正则.*c.*也无法正常工作,请问该如何修复这段代码?
修复方案
问题核心是当前规则逻辑错误:原代码的not_statement会在请求中任意内容不匹配Host头正则时触发统计,而非仅针对Host头本身的匹配结果。修正后需将匹配范围严格限定在Host头,再对“不匹配目标域名”的请求执行统计。
修正后的代码
resource "aws_wafv2_web_acl" "main" { name = "main" description = "统计非指定域名的请求" scope = "REGIONAL" default_action { allow {} } rule { name = "count_non_target_domains" priority = 1 action { count {} } statement { # 逻辑:仅当Host头不匹配指定域名列表时,触发统计 not_statement { statement { or_statement { statements { # 匹配 stg.sample.example.com string_match_statement { search_string = "stg.sample.example.com" field_to_match { single_header { name = "host" } } text_transformation { priority = 0 type = "NONE" } } } statements { # 匹配 api.stg.sample.example.com string_match_statement { search_string = "api.stg.sample.example.com" field_to_match { single_header { name = "host" } } text_transformation { priority = 0 type = "NONE" } } } statements { # 匹配 admin.stg.sample.example.com string_match_statement { search_string = "admin.stg.sample.example.com" field_to_match { single_header { name = "host" } } text_transformation { priority = 0 type = "NONE" } } } } } } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "count_non_target_domains" sampled_requests_enabled = true } } }
关键调整说明
- 严格限定匹配字段:所有匹配规则都明确指定
field_to_match为host头,完全避免其他Header(如referer)的内容干扰统计逻辑。 - 用精确匹配替代正则:对于固定域名,使用
string_match_statement比正则更高效且无歧义;如果需要支持通配符(如所有stg.sample.example.com的子域名),可改用regex_match_statement,正则表达式调整为^(api|admin\\.)?stg\\.sample\\.example\\.com$。 - 逻辑清晰化:通过
or_statement整合三个目标域名的匹配规则,再用not_statement取反,精准实现“仅Host头不在目标列表时统计”的需求。
内容的提问来源于stack exchange,提问作者52zxc
相关产品推荐
相关产品推荐

