CloudFront 與 WAF

🔥 Vibe Prompt

「設定 CloudFront 搭配 S3 來源、WAF 速率限制、地理封鎖、以及自訂網域與 SSL。」

CloudFront 分發設定

resource "aws_cloudfront_distribution" "cdn" {
  enabled = true
  price_class = "PriceClass_100"  # 僅美國、歐洲
  
  origin {
    domain_name = aws_s3_bucket_website_configuration.assets.website_endpoint
    origin_id   = "S3Assets"
    custom_origin_config {
      http_port = 80
      https_port = 443
      origin_protocol_policy = "https-only"
    }
  }
  
  default_cache_behavior {
    allowed_methods = ["GET", "HEAD"]
    cached_methods  = ["GET", "HEAD"]
    target_origin_id = "S3Assets"
    viewer_protocol_policy = "redirect-to-https"
    cache_policy_id = "658327ea-f89d-4fab-a63d-7e88639e58f6"
    compress = true
  }
  
  restrictions {
    geo_restriction {
      restriction_type = "whitelist"
      locations = ["TW", "US", "JP"]
    }
  }
  
  viewer_certificate {
    acm_certificate_arn = aws_acm_certificate.main.arn
    ssl_support_method = "sni-only"
  }
  
  web_acl_id = aws_wafv2_web_acl.main.arn
}

WAF 規則

resource "aws_wafv2_web_acl" "main" {
  name = "app-waf"
  scope = "CLOUDFRONT"
  default_action { allow {} }
  
  rule {
    name = "RateLimit"
    priority = 1
    action { block {} }
    statement {
      rate_based_statement {
        limit = 2000
        aggregate_key = "IP"
      }
    }
  }
  
  rule {
    name = "AWSManagedRules"
    priority = 2
    override_action { none {} }
    statement {
      managed_rule_group_statement {
        vendor_name = "AWS"
        name = "AWSManagedRulesCommonRuleSet"
      }
    }
  }
}

安全架構

使用者 → CloudFront (WAF) → Origin Shield → S3/ALB
          ├── 速率限制(每 IP 2000 req/min)
          ├── AWS 受管規則(SQL 注入、XSS)
          ├── 地理封鎖(白名單)
          └── 強制 HTTPS

最佳實踐

  • 使用 Origin Shield 減少來源負載
  • 啟用壓縮(gzip/brotli)
  • 設定快取策略最大化 TTL
  • 使用 AWS 受管 WAF 規則
  • 使用 PriceClass_100 降低成本

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!