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 降低成本


CloudFront + WAF:速度與安全的結合

CloudFront 是 AWS 的 CDN(內容傳遞網路),將你的內容快取在全球 450+ 邊緣節點。WAF(Web Application Firewall)則在 CloudFront 前面過濾惡意流量——兩者結合是 AWS 上靜態網站和 API 的標準部署方式。

CloudFront 的核心功能

| 功能 | 效果 | 什麼時候用 | |:----|:----|:---------| | 靜態快取 | HTML/CSS/JS 快取在邊緣節點 | 任何網站 | | Lambda@Edge | 在邊緣節點執行程式碼(URL 改寫、A/B 測試) | 需要邊緣運算 | | Origin Shield | 減少對原始伺服器的請求次數 | 高流量網站 | | SSL/TLS | 免費的 HTTPS 憑證 | 所有 production 網站 |

WAF 可以防護什麼?

  • SQL Injection:阻擋惡意 SQL 語法
  • XSS:阻擋跨站腳本攻擊
  • Rate Limit:限制單一 IP 的請求頻率
  • IP 黑名單:封鎖已知的惡意 IP 區段
  • 地理封鎖:限制只能從特定國家存取

下一章預告:IAM 與完整基礎設施

CloudFront 和 WAF 是安全與效能的 frontline。下一章的 IAM 則是最後的權限控管——沒有正確的 IAM 政策,前面的防護都可能是白費。

解鎖完整教學內容

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