Networking
D1 · Secure
D3 · Performance
~2 phút đọc

CloudFront deep-dive — origins, cache, signed URL, OAC

Cấu hình CloudFront sâu hơn: Origin Access Control thay OAI, cache key & policy, signed URL/cookie, edge functions.

cloudfront
cdn
oac
signed-url
edge

Sơ đồ tổng quan

Đang tải sơ đồ…

Origins

  • S3 bucket: khuyến nghị bật OAC (Origin Access Control) thay OAI cũ. OAC ký SigV4, hỗ trợ KMS-encrypted bucket, cross-region, cần bucket policy cho phép principal `cloudfront.amazonaws.com`.
  • Custom origin (ALB, EC2, bên thứ ba): HTTPS + SNI, custom header để chặn bypass CDN (CloudFront thêm header secret → ALB chỉ accept khi có header).
  • Origin Groups: primary + secondary với failover theo HTTP status code (500/502/503/504 hoặc 4xx nếu bật).

Cache behaviors & policies

  • Path pattern ưu tiên theo thứ tự khai báo (specific trước, default cuối).
  • Cache Policy (managed hoặc custom): TTL (min/default/max), headers/cookies/query strings thuộc cache key.
  • Origin Request Policy: fields gửi xuống origin NHƯNG không nằm trong cache key. Tách biệt với cache policy.
  • Response Headers Policy: thêm CORS, HSTS, custom header mà không đụng origin.
Tip
Muốn cache theo device type? Dùng header CloudFront-Is-Mobile-Viewer trong cache key, đừng forward User-Agent (cardinality quá lớn → cache miss).

Bảo vệ nội dung

  • Signed URL: 1 URL cho 1 file → phù hợp single download (video, PDF).
  • Signed Cookie: 1 cookie bao nhiều file theo policy (wildcard path) → phù hợp web app nhiều asset.
  • Trusted Key Groups (mới) thay Trusted Signers (legacy root account key). Key group gán cho behavior.
  • Field-Level Encryption: encrypt một vài field (credit card) ở edge, chỉ origin có private key decrypt.
  • Geo Restriction: whitelist/blacklist quốc gia.

Edge functions: chọn cái nào?

  • CloudFront Functions: JS thuần, chỉ ở Viewer Request/Response, chạy dưới 1ms, không gọi network, dùng cho URL rewrite / header manipulation / A/B split / JWT verify đơn giản.
  • Lambda@Edge: Node.js/Python, có thể gọi AWS SDK, ở 4 event (Viewer Req/Res, Origin Req/Res), deploy từ us-east-1, dùng cho xử lý phức tạp (image resize, auth với RDS/DDB).

Block bypass CDN

ALB origin có thể bị hit thẳng qua DNS của ALB nếu không bảo vệ. Cách chuẩn: CloudFront thêm custom header secret (`X-Origin-Secret: ...`) vào request tới origin; ALB listener rule chỉ forward nếu header khớp, else trả 403.

Bucket policy cho S3 origin dùng OAC
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "cloudfront.amazonaws.com" },
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/*",
    "Condition": {
      "StringEquals": {
        "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/E1ABCDEF"
      }
    }
  }]
}