AWS Documentation · Tiếng Việt

Amazon CloudFront

Dịch vụ mạng phân phối nội dung (CDN) toàn cầu với độ trễ thấp, tốc độ truyền tải cao — Tài liệu toàn diện từ kiến trúc đến vận hành

Cập nhật 04/2026
Networking · CDN
AWS Core Service
01 · Tổng quan

CloudFront là gì?

Amazon CloudFront là dịch vụ mạng phân phối nội dung (Content Delivery Network — CDN) toàn cầu của AWS. CloudFront phân phối dữ liệu, video, ứng dụng và API đến người dùng cuối với độ trễ thấp và tốc độ truyền tải cao thông qua mạng lưới hơn 600+ Points of Presence (PoPs) trên toàn thế giới.

🌍
600+ Edge Locations
Mạng lưới PoPs phủ khắp 6 châu lục, đưa nội dung đến gần người dùng nhất.
Độ trễ cực thấp
Cache nội dung tại edge, giảm latency từ hàng trăm ms xuống còn vài ms.
🛡️
Bảo mật tích hợp
DDoS protection (Shield), WAF, SSL/TLS, Signed URLs, Field-Level Encryption.
💰
Pay-per-use
Trả tiền theo lượng data transfer ra + số request. Không phí tối thiểu.
🔗
Tích hợp sâu AWS
Kết nối S3, ALB, EC2, Lambda@Edge, API Gateway, MediaStore, MediaPackage.
🧩
Edge Computing
Chạy code tại edge với Lambda@Edge và CloudFront Functions — không cần server.

Use Cases phổ biến

  • Static Website Acceleration: Phân phối HTML, CSS, JS, hình ảnh từ S3 qua CloudFront
  • Dynamic Content Delivery: Tăng tốc API responses, dynamic pages từ ALB/EC2
  • Video Streaming: Live streaming và VOD (Video on Demand) với HLS, DASH
  • Software Distribution: Phân phối packages, game patches, firmware updates
  • API Acceleration: Giảm latency cho REST/GraphQL API qua edge routing
  • Security at Edge: Chặn DDoS, bot, geo-restriction trước khi request đến origin

So sánh CloudFront vs các CDN khác

Tiêu chíCloudFrontCloudflareAkamai
Edge Locations600+ PoPs300+ PoPs4,000+ PoPs
Tích hợp AWSNativeQua API/DNSQua API/DNS
Edge ComputingLambda@Edge, CF FunctionsWorkersEdgeWorkers
DDoS ProtectionShield Standard (miễn phí)Có (miễn phí)Có (trả phí)
Free Tier1 TB/tháng (12 tháng đầu)Unlimited (plan free)Không
Origin ShieldTiered CacheSureRoute
💡 Khi nào chọn CloudFront?
Chọn CloudFront khi hệ thống chạy trên AWS và cần tích hợp native với S3, ALB, API Gateway. CloudFront cũng là lựa chọn tốt khi bạn cần edge computing (Lambda@Edge) và bảo mật tích hợp (WAF, Shield) mà không cần cấu hình phức tạp.
02 · Kiến trúc

Kiến trúc CloudFront

CloudFront CDN Architecture — Sơ đồ kiến trúc Scroll / zoom · Mở draw.io ↗

CloudFront hoạt động dựa trên kiến trúc 3 tầng: Edge Locations, Regional Edge CachesOrigin. Khi người dùng request nội dung, CloudFront tự động route đến edge location gần nhất thông qua AWS global network.

KIẾN TRÚC CLOUDFRONT — LUỒNG REQUEST 👤 Người dùng Browser / App DNS ⚡ Edge Location 600+ PoPs toàn cầu Cache Layer 1 CF Functions chạy tại đây Cache Miss 🏢 Regional Edge 13 Regional Caches Cache Layer 2 (lớn hơn) Lambda@Edge chạy tại đây Miss 🏠 Origin S3 / ALB / EC2 API Gateway Custom HTTP ✓ Cache Hit — Trả về ngay 🛡️ Origin Shield (Tùy chọn) Cache Layer 3 Luồng xử lý request: 1. Người dùng gửi request → DNS resolve đến Edge Location gần nhất (Route 53 / Anycast) 2. Edge Location kiểm tra cache → Nếu HIT → trả về ngay (latency thấp nhất) 3. Nếu MISS → chuyển đến Regional Edge Cache → Nếu HIT → trả về + cache tại Edge 4. Nếu vẫn MISS → request đến Origin (qua Origin Shield nếu bật) → cache kết quả tại cả 2 tầng

Edge Locations

Edge Locations là các data center nhỏ nằm rải rác khắp thế giới, nơi CloudFront cache nội dung. Khi người dùng request, CloudFront route đến edge location gần nhất dựa trên latency.

  • 600+ PoPs tại hơn 90 thành phố, 47 quốc gia
  • Mỗi edge location có cache riêng, xử lý SSL termination
  • CloudFront Functions chạy tại tất cả edge locations
  • Tự động scale theo traffic — không cần provision

Regional Edge Caches

Regional Edge Caches là tầng cache trung gian giữa Edge Locations và Origin. Chúng có dung lượng cache lớn hơn, giúp giữ nội dung lâu hơn trước khi bị evict.

  • 13 Regional Edge Caches trên toàn cầu
  • Cache size lớn hơn → content tồn tại lâu hơn
  • Lambda@Edge chạy tại regional edge caches
  • Giảm tải cho origin khi nhiều edge locations cùng miss cache

Origin Types

Origin TypeMô tảUse Case
S3 BucketStatic files (HTML, CSS, JS, images)Static website, media
ALB / ELBApplication Load Balancer (phải public)Dynamic web app, API
EC2 InstanceInstance trực tiếp (phải public IP)Custom web server
API GatewayREST/HTTP API endpointServerless API
MediaStoreAWS media servicesVideo streaming
Custom HTTPBất kỳ HTTP server nàoHybrid / multi-cloud
💡 Origin Failover
CloudFront hỗ trợ Origin Groups với primary + secondary origin. Khi primary trả về lỗi (5xx), CloudFront tự động failover sang secondary — tăng high availability.
03 · Distributions

Distributions

Một Distribution là đơn vị cấu hình chính của CloudFront. Mỗi distribution có một domain name duy nhất (vd: d1234abcd.cloudfront.net) và chứa toàn bộ cấu hình về origins, cache behaviors, SSL, security.

Các loại Distribution

LoạiTrạng tháiMô tả
Web Distribution Active Phân phối nội dung qua HTTP/HTTPS. Hỗ trợ static + dynamic content, WebSocket, streaming.
RTMP Distribution Deprecated Streaming media qua RTMP protocol. Đã ngừng hỗ trợ từ 12/2020. Dùng HLS/DASH thay thế.
CẤU TRÚC CLOUDFRONT DISTRIBUTION 📦 Distribution: d1234abcd.cloudfront.net Origins 🪣 S3: my-bucket.s3 ⚖️ ALB: my-alb.elb 🌐 Custom: api.example.com 🔄 Origin Group (failover) Cache Behaviors Default (*) → S3 | TTL: 86400s /api/* → ALB | TTL: 0 | Forward All /images/* → S3 | TTL: 604800s /static/* → S3 | TTL: 2592000s Settings 🔒 SSL: ACM Certificate 🌐 CNAME: cdn.example.com 💰 Price Class: All Locations 🛡️ WAF: web-acl-id 📝 Logging: logs-bucket ⚡ HTTP/2, HTTP/3: Enabled 📄 Root Object: index.html

Origin Groups — Failover

Origin Groups cho phép cấu hình automatic failover giữa primary và secondary origin:

Origin Group Config (JSON)
// Khi primary origin trả về 500/502/503/504
// → CloudFront tự động chuyển sang secondary
{
  "OriginGroup": {
    "Id": "my-origin-group",
    "FailoverCriteria": {
      "StatusCodes": { "Items": [500, 502, 503, 504] }
    },
    "Members": {
      "Items": [
        { "OriginId": "primary-s3-us-east-1" },
        { "OriginId": "secondary-s3-eu-west-1" }
      ]
    }
  }
}
⚠️ Thời gian deploy
Sau khi tạo hoặc cập nhật distribution, CloudFront cần 5-15 phút để propagate cấu hình đến tất cả edge locations. Status chuyển từ InProgress sang Deployed.
04 · Cache Behaviors

Cache Behaviors

Cache Behaviors là thành phần quan trọng nhất trong cấu hình CloudFront. Mỗi behavior định nghĩa cách CloudFront xử lý request dựa trên path pattern, bao gồm: origin nào sẽ nhận request, cách cache, headers/cookies/query strings nào được forward.

Path Pattern Matching

CloudFront đánh giá path patterns theo thứ tự từ trên xuống. Request khớp với pattern đầu tiên sẽ được xử lý bởi behavior tương ứng. Nếu không khớp pattern nào → dùng Default (*) behavior.

Path PatternVí dụ URL khớpOriginGhi chú
/api/*/api/users, /api/v2/ordersALBForward all headers, no cache
/images/*.jpg/images/photo.jpgS3Cache lâu, compress
/static/*/static/app.js, /static/style.cssS3Immutable, TTL dài
/video/*/video/intro.mp4MediaStoreStreaming optimized
Default (*)Tất cả URL còn lạiS3Fallback behavior

TTL (Time to Live)

TTL quyết định thời gian CloudFront giữ object trong cache trước khi kiểm tra lại origin:

Cấu hìnhGiá trịMô tả
Minimum TTL0 giây (mặc định)Thời gian tối thiểu cache, bất kể origin header
Default TTL86,400 giây (24h)Áp dụng khi origin không gửi Cache-Control/Expires
Maximum TTL31,536,000 giây (365 ngày)Giới hạn trên, dù origin header yêu cầu lâu hơn
💡 TTL Priority
  • Nếu origin gửi Cache-Control: max-age=3600 → CloudFront dùng 3600s (nếu nằm trong min-max range)
  • Nếu origin gửi Cache-Control: no-cache hoặc no-store → CloudFront vẫn cache nhưng revalidate mỗi request
  • Nếu origin không gửi header nào → dùng Default TTL
  • Cache-Control: s-maxage được ưu tiên hơn max-age cho shared caches (CDN)

Forwarded Values — Cache Key

CloudFront tạo cache key từ URL + các giá trị bạn chọn forward. Càng nhiều giá trị forward → cache key càng unique → cache hit rate giảm.

Headers

  • None (khuyến nghị cho static): Không forward header → cache key chỉ dựa trên URL → hit rate cao nhất
  • Whitelist: Forward một số headers cụ thể (vd: Accept-Language, Authorization)
  • All: Forward tất cả headers → mỗi request unique → không cache (dùng cho dynamic content)

Query Strings

  • None: Bỏ qua query strings → /page?v=1/page?v=2 cùng cache key
  • Whitelist: Chỉ include một số params (vd: id, lang)
  • All: Include tất cả query strings vào cache key
  • All-Except: Include tất cả trừ một số params

Cookies

  • None (khuyến nghị): Không forward cookies → tốt cho static content
  • Whitelist: Forward cookies cụ thể (vd: session_id)
  • All: Forward tất cả cookies → cache key rất unique

Cache Policy vs Origin Request Policy

✅ Cache Policy
  • Quyết định cache key gồm những gì
  • Cấu hình TTL (min, default, max)
  • Headers, cookies, query strings nào tham gia cache key
  • Compression support (Gzip, Brotli)
  • Managed policies: CachingOptimized, CachingDisabled
📤 Origin Request Policy
  • Quyết định gửi gì đến origin khi cache miss
  • Forward thêm headers, cookies, query strings
  • Không ảnh hưởng cache key
  • Managed policies: AllViewer, CORS-S3Origin
  • Dùng khi origin cần thông tin mà cache key không cần
Ví dụ: Tạo Cache Policy (AWS CLI)
# Tạo custom cache policy
aws cloudfront create-cache-policy \
  --cache-policy-config '{
    "Name": "MyCustomCachePolicy",
    "DefaultTTL": 86400,
    "MinTTL": 1,
    "MaxTTL": 31536000,
    "ParametersInCacheKeyAndForwardedToOrigin": {
      "EnableAcceptEncodingGzip": true,
      "EnableAcceptEncodingBrotli": true,
      "HeadersConfig": {
        "HeaderBehavior": "whitelist",
        "Headers": { "Items": ["Accept-Language"], "Quantity": 1 }
      },
      "CookiesConfig": { "CookieBehavior": "none" },
      "QueryStringsConfig": {
        "QueryStringBehavior": "whitelist",
        "QueryStrings": { "Items": ["id", "page"], "Quantity": 2 }
      }
    }
  }'
05 · Origin Access Control

Origin Access Control (OAC) & Origin Access Identity (OAI)

Khi dùng S3 làm origin, bạn muốn chỉ cho phép CloudFront truy cập bucket — chặn truy cập trực tiếp từ internet. AWS cung cấp 2 cơ chế: OAC (mới, khuyến nghị) và OAI (cũ, legacy).

So sánh OAC vs OAI

Tiêu chíOAC (Khuyến nghị)OAI (Legacy)
Hỗ trợ SSE-KMSKhông
Hỗ trợ S3 PUT/DELETEChỉ GET
Hỗ trợ tất cả Region
SigV4 signingKhông
Hỗ trợ S3 Object LambdaKhông
Trạng tháiRecommendedLegacy

Cấu hình OAC

Bước 1: Tạo OAC
aws cloudfront create-origin-access-control \
  --origin-access-control-config '{
    "Name": "my-s3-oac",
    "Description": "OAC for S3 bucket",
    "SigningProtocol": "sigv4",
    "SigningBehavior": "always",
    "OriginAccessControlOriginType": "s3"
  }'
Bước 2: S3 Bucket Policy cho OAC
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowCloudFrontOAC",
    "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/EDFDVBD6EXAMPLE"
      }
    }
  }]
}

OAI (Legacy) — Tham khảo

S3 Bucket Policy cho OAI
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1234567890"
    },
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/*"
  }]
}
🚨 Quan trọng cho SAA Exam
  • OAC là best practice hiện tại — luôn chọn OAC trong câu hỏi mới
  • OAI không hỗ trợ SSE-KMS encryption — nếu đề bài nhắc KMS → chọn OAC
  • OAC hỗ trợ cả PUT/DELETE → dùng cho upload qua CloudFront
  • Bucket phải Block Public Access = ON khi dùng OAC/OAI
06 · SSL/TLS & Custom Domains

SSL/TLS & Custom Domains

CloudFront hỗ trợ HTTPS cho cả viewer-facing (client → edge) và origin-facing (edge → origin). Bạn có thể dùng custom domain name (CNAME) với SSL certificate từ AWS Certificate Manager (ACM).

Viewer Protocol Policy

PolicyHành viKhuyến nghị
HTTP and HTTPSCho phép cả HTTP và HTTPSKhông khuyến nghị
Redirect HTTP to HTTPSTự động redirect HTTP → HTTPS (301)Khuyến nghị
HTTPS OnlyChỉ chấp nhận HTTPS, reject HTTPCho API, sensitive data

Origin Protocol Policy

PolicyMô tảGhi chú
HTTP OnlyCloudFront → Origin qua HTTPS3 website endpoint chỉ hỗ trợ HTTP
HTTPS OnlyCloudFront → Origin qua HTTPSALB, custom origin với SSL
Match ViewerDùng cùng protocol với viewerLinh hoạt nhưng cần origin hỗ trợ cả 2

SSL Certificate Options

SSL/TLS — HAI PHƯƠNG THỨC ✅ SNI (Server Name Indication) • Miễn phí — không phí thêm • Client gửi hostname trong TLS handshake • Hỗ trợ hầu hết browser hiện đại → Khuyến nghị cho hầu hết use cases Không hỗ trợ: IE trên Windows XP, Android < 4.0 💰 Dedicated IP SSL • $600/tháng/distribution • Mỗi edge location có dedicated IP • Hỗ trợ tất cả client (kể cả cũ) → Chỉ dùng khi cần hỗ trợ legacy client Rất đắt — tránh nếu không cần thiết

Cấu hình Custom Domain với ACM

  1. Request certificate từ ACM — phải ở region us-east-1 (N. Virginia)
  2. Validate domain — DNS validation (khuyến nghị) hoặc Email validation
  3. Thêm CNAME vào distribution — Alternate Domain Names: cdn.example.com
  4. Tạo DNS record — CNAME hoặc Alias record trỏ đến d1234.cloudfront.net
Request ACM Certificate (phải ở us-east-1)
# Certificate cho CloudFront PHẢI ở us-east-1
aws acm request-certificate \
  --region us-east-1 \
  --domain-name cdn.example.com \
  --subject-alternative-names "*.example.com" \
  --validation-method DNS

# Sau khi validate, gán vào distribution
aws cloudfront update-distribution \
  --id E1234567890 \
  --distribution-config '{
    "ViewerCertificate": {
      "ACMCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/abc-123",
      "SSLSupportMethod": "sni-only",
      "MinimumProtocolVersion": "TLSv1.2_2021"
    },
    "Aliases": { "Items": ["cdn.example.com"], "Quantity": 1 }
  }'
🚨 Lỗi thường gặp
  • ACM certificate cho CloudFront bắt buộc phải ở us-east-1 — tạo ở region khác sẽ không thấy trong dropdown
  • CNAME trong distribution phải khớp với domain trong certificate
  • Không thể dùng cùng CNAME cho 2 distributions khác nhau
07 · Cache Invalidation & Versioning

Cache Invalidation & Versioning

Khi bạn cập nhật nội dung tại origin, CloudFront vẫn serve bản cũ từ cache cho đến khi TTL hết hạn. Có 2 cách để người dùng nhận nội dung mới: Invalidation (xóa cache) và Versioning (đổi URL).

Cache Invalidation

Invalidation yêu cầu CloudFront xóa object khỏi cache tại tất cả edge locations. Object sẽ được fetch lại từ origin ở request tiếp theo.

Tạo Invalidation (AWS CLI)
# Invalidate một file cụ thể
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/index.html"

# Invalidate nhiều files
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/images/*" "/css/*" "/js/*"

# Invalidate TẤT CẢ (wildcard)
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/*"

# Kiểm tra trạng thái invalidation
aws cloudfront get-invalidation \
  --distribution-id E1234567890 \
  --id I1234567890
Tiêu chíChi tiết
Thời gian hoàn thànhThường 1-2 phút, tối đa 10-15 phút
Miễn phí1,000 invalidation paths/tháng (mỗi /* tính 1 path)
Phí vượt$0.005/path sau 1,000 paths
Giới hạn đồng thờiTối đa 3,000 invalidation paths đang xử lý
WildcardHỗ trợ * ở cuối path (vd: /images/*)

File Versioning (Khuyến nghị)

Thay vì invalidate cache, best practice là dùng versioned file names. Khi nội dung thay đổi, đổi tên file → CloudFront tự động fetch bản mới.

❌ Invalidation (tránh nếu có thể)
  • Tốn phí sau 1,000 paths/tháng
  • Mất 1-15 phút để propagate
  • Không đảm bảo tất cả edge đồng bộ cùng lúc
  • Khó rollback nếu deploy lỗi
✅ Versioning (best practice)
  • Miễn phí — không tốn invalidation cost
  • Hiệu lực ngay lập tức
  • Dễ rollback — chỉ cần trỏ lại URL cũ
  • Ví dụ: /app.v2.js, /style.abc123.css
💡 Chiến lược kết hợp
  • Static assets (JS, CSS, images): Dùng versioned filenames + TTL dài (1 năm)
  • HTML files: TTL ngắn (vài phút) hoặc no-cache + invalidate khi deploy
  • API responses: TTL = 0 hoặc rất ngắn, forward relevant headers
08 · Edge Computing

Lambda@Edge & CloudFront Functions

CloudFront cho phép chạy code tại edge để customize request/response mà không cần thay đổi origin. Có 2 lựa chọn: CloudFront Functions (lightweight, nhanh) và Lambda@Edge (mạnh mẽ, linh hoạt).

4 EVENT TRIGGERS — CLOUDFRONT FUNCTIONS & LAMBDA@EDGE 👤 Viewer Client ① Viewer Request CF Functions + Lambda@Edge CloudFront Cache Layer Edge Location ② Origin Request Lambda@Edge only 🏠 Origin S3 / ALB ③ Origin Response Lambda@Edge only ④ Viewer Response CF Functions + Lambda@Edge CF Functions: ① Viewer Request + ④ Viewer Response | Lambda@Edge: ① ② ③ ④ (tất cả 4 events)

So sánh CloudFront Functions vs Lambda@Edge

Tiêu chíCloudFront FunctionsLambda@Edge
RuntimeJavaScript (ECMAScript 5.1)Node.js, Python
Chạy tạiTất cả Edge Locations (600+)Regional Edge Caches (13)
EventsViewer Request, Viewer ResponseTất cả 4 events
Execution time< 1ms5s (viewer) / 30s (origin)
Memory2 MB128 MB – 10 GB
Package size10 KB50 MB (zipped)
Network accessKhông
File systemKhôngCó (/tmp)
Request body accessKhông
Giá$0.10/1M invocations$0.60/1M invocations + duration
Scale10,000,000 req/s10,000 req/s/region

Ví dụ: CloudFront Function — URL Rewrite

CloudFront Function: Thêm index.html cho SPA
function handler(event) {
  var request = event.request;
  var uri = request.uri;

  // Nếu URI không có extension → thêm /index.html
  if (uri.endsWith('/')) {
    request.uri += 'index.html';
  } else if (!uri.includes('.')) {
    request.uri += '/index.html';
  }

  return request;
}

Ví dụ: Lambda@Edge — A/B Testing

Lambda@Edge: Origin Request — A/B Testing
'use strict';
exports.handler = async (event) => {
  const request = event.Records[0].cf.request;
  const headers = request.headers;

  // Đọc cookie để xác định variant
  const cookie = headers.cookie || [];
  const abCookie = cookie.find(c =>
    c.value.includes('X-AB-Variant=')
  );

  if (abCookie && abCookie.value.includes('B')) {
    // Route đến origin B
    request.origin.s3.domainName = 'variant-b-bucket.s3.amazonaws.com';
    request.headers['host'] = [{ value: 'variant-b-bucket.s3.amazonaws.com' }];
  }

  return request;
};

Use Cases phổ biến

🔀
URL Rewrite
Thêm index.html, redirect www → non-www, normalize URLs. Dùng CF Functions.
🔐
Auth at Edge
Validate JWT token, check API key trước khi đến origin. Dùng CF Functions hoặc Lambda@Edge.
🧪
A/B Testing
Route traffic đến các origin khác nhau dựa trên cookie/header. Dùng Lambda@Edge.
🌐
Geo-based Content
Serve nội dung khác nhau theo quốc gia (CloudFront-Viewer-Country header).
🖼️
Image Optimization
Resize, convert format (WebP) on-the-fly tại edge. Dùng Lambda@Edge.
📝
Security Headers
Thêm HSTS, CSP, X-Frame-Options vào response. Dùng CF Functions.
09 · Bảo mật

Security

CloudFront cung cấp nhiều lớp bảo mật từ edge đến origin: AWS WAF, AWS Shield, Geo Restriction, Signed URLs/Cookies, và Field-Level Encryption.

AWS WAF Integration

AWS WAF (Web Application Firewall) có thể gắn trực tiếp vào CloudFront distribution để lọc request tại edge:

  • Rate limiting: Chặn IP gửi quá nhiều request
  • IP whitelist/blacklist: Cho phép/chặn IP ranges
  • SQL injection & XSS protection: Managed rules từ AWS
  • Bot control: Phát hiện và chặn bot traffic
  • Geo-based rules: Chặn theo quốc gia
  • Custom rules: Dựa trên headers, query strings, body
💡 WAF + CloudFront
WAF rules được evaluate tại edge location — request bị chặn sẽ không bao giờ đến origin. Điều này giúp bảo vệ origin và giảm chi phí.

Geo Restriction (Geoblocking)

LoạiMô tảVí dụ
WhitelistChỉ cho phép truy cập từ các quốc gia được chọnChỉ cho VN, US, JP
BlacklistChặn truy cập từ các quốc gia được chọnChặn CN, RU

CloudFront xác định quốc gia dựa trên IP address và thêm header CloudFront-Viewer-Country vào request.

Signed URLs & Signed Cookies

Dùng để hạn chế truy cập nội dung — chỉ người có URL/cookie hợp lệ mới xem được:

🔗 Signed URLs
  • Mỗi URL chỉ truy cập được 1 file
  • Có thời hạn (expiration time)
  • Có thể giới hạn IP range
  • Dùng cho: download file, video streaming
  • Tương thích với mọi client
🍪 Signed Cookies
  • Truy cập được nhiều files cùng lúc
  • Không thay đổi URL gốc
  • Có thời hạn + IP restriction
  • Dùng cho: subscription content, premium area
  • Cần client hỗ trợ cookies

Signed URL vs S3 Pre-signed URL

Tiêu chíCloudFront Signed URLS3 Pre-signed URL
Truy cập quaCloudFront (edge cache)S3 trực tiếp
Caching — serve từ edgeKhông — luôn đến S3
IP restrictionKhông
Path restrictionCó (canned/custom policy)Chỉ 1 object
Ký bằngCloudFront key pair (trusted key group)IAM credentials
Khi nào dùngPhân phối content qua CDNTruy cập S3 trực tiếp (upload/download)

Field-Level Encryption

Field-Level Encryption cho phép mã hóa các trường nhạy cảm (credit card, SSN) ngay tại edge location. Dữ liệu được mã hóa bằng public key và chỉ application server có private key mới giải mã được.

  • Mã hóa tại edge → dữ liệu nhạy cảm được bảo vệ suốt đường truyền
  • Chỉ áp dụng cho POST requests với specific fields
  • Dùng RSA encryption với public/private key pair
  • Tối đa 10 fields có thể encrypt

AWS Shield

TierGiáBảo vệ
Shield StandardMiễn phíTự động bảo vệ DDoS Layer 3/4 cho tất cả CloudFront distributions
Shield Advanced$3,000/thángDDoS Layer 3/4/7, DDoS Response Team (DRT), cost protection, WAF miễn phí
10 · Hiệu năng

Performance Optimization

CloudFront cung cấp nhiều tính năng để tối ưu hiệu năng: Compression, HTTP/2 & HTTP/3, Origin Shield, và Price Classes.

Compression

CloudFront có thể tự động compress nội dung trước khi gửi đến viewer, giảm bandwidth và tăng tốc tải trang:

CompressionHỗ trợGhi chú
GzipHỗ trợ rộng rãi, giảm 60-80% kích thước text files
BrotliNén tốt hơn Gzip 15-25%, hỗ trợ browser hiện đại
  • Bật trong Cache Policy: EnableAcceptEncodingGzipEnableAcceptEncodingBrotli
  • CloudFront tự chọn Gzip hoặc Brotli dựa trên Accept-Encoding header của viewer
  • Chỉ compress files từ 1,000 bytes đến 10 MB
  • Compress các content types: text/html, text/css, application/javascript, application/json, v.v.

HTTP/2 & HTTP/3

ProtocolTính năngLợi ích
HTTP/2 Multiplexing, header compression, server push Tải nhiều files song song trên 1 connection, giảm latency
HTTP/3 (QUIC) UDP-based, 0-RTT handshake, better loss recovery Nhanh hơn trên mạng không ổn định (mobile, WiFi), giảm connection setup time
💡 HTTP/3
HTTP/3 được bật mặc định cho CloudFront distributions mới. Nó đặc biệt hiệu quả cho mobile users và mạng có packet loss cao. Client tự động fallback về HTTP/2 nếu không hỗ trợ HTTP/3.

Origin Shield

Origin Shield là một tầng cache bổ sung giữa Regional Edge Caches và Origin. Nó hoạt động như một "single point of contact" cho origin, giảm đáng kể số request đến origin.

ORIGIN SHIELD — GIẢM TẢI CHO ORIGIN ❌ Không có Origin Shield Edge US Edge EU Edge AP Origin (3 req) 3 requests đến origin ✅ Có Origin Shield Edge US Edge EU Edge AP Origin Shield Origin (1 req)
  • Khi nào dùng: Viewers phân tán nhiều region, origin không chịu được nhiều request
  • Chọn region: Chọn region gần origin nhất để giảm latency
  • Chi phí: Tính thêm phí cho request qua Origin Shield
  • Lợi ích: Tăng cache hit ratio, giảm origin load, giảm chi phí origin

Price Classes

Price Classes cho phép bạn giới hạn edge locations mà CloudFront sử dụng, giúp giảm chi phí:

Price ClassEdge LocationsChi phíKhi nào dùng
Price Class All Tất cả 600+ PoPs Cao nhất Cần performance tốt nhất toàn cầu
Price Class 200 Hầu hết regions (trừ South America, Australia) Trung bình Cân bằng giá/performance
Price Class 100 Chỉ North America + Europe Thấp nhất Users chủ yếu ở US/EU
⚠️ Lưu ý Price Class
Khi dùng Price Class 100, users ở Asia vẫn truy cập được nhưng sẽ bị route đến edge location ở US/EU → latency cao hơn. CloudFront không chặn truy cập, chỉ giới hạn edge locations.
11 · Monitoring

Monitoring & Logging

CloudFront cung cấp nhiều công cụ giám sát: CloudWatch Metrics, Standard Access Logs, và Real-time Logs.

CloudWatch Metrics

CloudFront tự động gửi metrics đến CloudWatch (miễn phí). Các metrics quan trọng:

MetricMô tảAlarm gợi ý
RequestsTổng số HTTP/HTTPS requestsSpike detection (anomaly)
BytesDownloadedBytes gửi từ CloudFront đến viewersBandwidth monitoring
BytesUploadedBytes gửi từ viewers đến CloudFront (POST/PUT)Upload monitoring
4xxErrorRate% requests trả về 4xx> 5% → alarm
5xxErrorRate% requests trả về 5xx> 1% → alarm
TotalErrorRate% tổng requests lỗi> 5% → alarm
CacheHitRate% requests served từ cache< 80% → investigate
OriginLatencyThời gian origin xử lý request (ms)> 2000ms → alarm
💡 Additional Metrics
Bật Additional Metrics (có phí) để xem thêm: Cache Hit Rate by status code, Origin Latency, Error Rate by status code. Rất hữu ích cho troubleshooting.

Standard Access Logs

CloudFront có thể ghi log mỗi request vào S3 bucket. Log file chứa thông tin chi tiết:

  • Timestamp, Client IP, HTTP method, URI, Status code
  • Edge location xử lý request
  • Cache result: Hit, Miss, RefreshHit, Error
  • Time taken: Thời gian xử lý (seconds)
  • User-Agent, Referer, Query string
  • SSL protocol, cipher
Ví dụ: Dòng log CloudFront
#Fields: date time x-edge-location sc-bytes c-ip cs-method cs(Host) cs-uri-stem sc-status cs(Referer) cs(User-Agent) cs-uri-query cs(Cookie) x-edge-result-type x-edge-request-id
2026-04-14  08:30:15  SIN2-C1  12345  203.0.113.50  GET  d1234.cloudfront.net  /images/logo.png  200  https://example.com/  Mozilla/5.0...  -  -  Hit  AbCdEf123==
⚠️ Lưu ý Access Logs
  • Logs được ghi vào S3 với delay 1-24 giờ (không real-time)
  • Log bucket phải ở cùng account, bật ACL cho CloudFront
  • Không tính phí CloudFront cho logging, nhưng tính phí S3 storage
  • Dùng Athena để query logs hiệu quả

Real-time Logs

Nếu cần log gần real-time (vài giây), dùng Real-time Logs → gửi đến Kinesis Data Streams:

  • Latency: Vài giây (so với hàng giờ của standard logs)
  • Destination: Kinesis Data Streams → có thể xử lý bằng Lambda, Kinesis Data Firehose → S3/OpenSearch/Splunk
  • Sampling rate: Có thể cấu hình 1-100% requests
  • Fields: Chọn fields cần log (giảm chi phí Kinesis)
  • Chi phí: Tính phí Kinesis Data Streams + CloudFront real-time log fee
Tạo Real-time Log Config
aws cloudfront create-realtime-log-config \
  --name my-realtime-logs \
  --sampling-rate 100 \
  --fields "timestamp" "c-ip" "sc-status" "cs-uri-stem" \
           "x-edge-result-type" "time-taken" \
  --end-points '{
    "StreamType": "Kinesis",
    "KinesisStreamConfig": {
      "RoleARN": "arn:aws:iam::111122223333:role/CloudFrontRealtimeLogRole",
      "StreamARN": "arn:aws:kinesis:us-east-1:111122223333:stream/cf-realtime-logs"
    }
  }'

Monitoring Architecture

CLOUDFRONT MONITORING ARCHITECTURE CloudFront Distribution 📊 CloudWatch Metrics + Alarms 🪣 S3 Access Logs Standard (1-24h delay) 🔥 Kinesis Streams Real-time (vài giây) 🔍 Athena SQL Query Logs 📈 OpenSearch Dashboard / Alert 📧 SNS / PagerDuty Alert Notification
12 · Troubleshooting & Best Practices

Các lỗi thường gặp & Best Practices

Lỗi thường gặp

LỗiNguyên nhânCách khắc phục
403 Access Denied S3 bucket policy không cho phép CloudFront, OAC/OAI chưa cấu hình đúng Kiểm tra bucket policy, đảm bảo OAC/OAI được gán đúng distribution
502 Bad Gateway CloudFront không kết nối được origin, SSL mismatch, origin timeout Kiểm tra origin health, SSL certificate, security group cho ALB/EC2
503 Service Unavailable Origin quá tải, CloudFront rate limiting Scale origin, bật Origin Shield, tăng TTL để giảm origin requests
504 Gateway Timeout Origin xử lý quá lâu (> 30s mặc định) Tăng origin response timeout (tối đa 180s), optimize origin
Stale content Cache chưa hết hạn, TTL quá dài Invalidate cache hoặc dùng versioned filenames
CORS errors Origin không trả CORS headers, CloudFront không forward Origin header Forward Origin header, cấu hình CORS tại origin, dùng Response Headers Policy
SSL certificate error ACM cert không ở us-east-1, cert expired, domain mismatch Tạo cert ở us-east-1, renew cert, kiểm tra CNAME khớp cert
Low cache hit rate Forward quá nhiều headers/cookies/query strings Giảm forwarded values, dùng Cache Policy tối ưu

Debugging Headers

CloudFront thêm các headers hữu ích vào response để debug:

Response Headers từ CloudFront
# Cache result
X-Cache: Hit from cloudfront        # Served từ cache
X-Cache: Miss from cloudfront       # Fetch từ origin
X-Cache: RefreshHit from cloudfront  # Cache expired, revalidated

# Edge location xử lý request
X-Amz-Cf-Pop: SIN2-C1              # Singapore edge location

# Request ID (dùng cho support ticket)
X-Amz-Cf-Id: AbCdEf123456789==

# Age (seconds object đã ở trong cache)
Age: 3600                           # Đã cache 1 giờ

# Kiểm tra bằng curl
curl -I https://cdn.example.com/index.html

Best Practices

📁
Versioned Assets
Dùng hash trong filename (app.a1b2c3.js) thay vì invalidation. TTL dài cho static assets.
🗜️
Bật Compression
Enable Gzip + Brotli trong Cache Policy. Giảm 60-80% bandwidth cho text-based content.
🛡️
Dùng OAC
Luôn dùng OAC (không phải OAI) cho S3 origin. Block Public Access trên bucket.
🔒
HTTPS Everywhere
Redirect HTTP → HTTPS. Dùng TLSv1.2_2021 minimum. ACM cert ở us-east-1.
📊
Monitor Cache Hit Rate
Mục tiêu > 90% cache hit rate. Giảm forwarded values nếu thấp.
🌐
Origin Shield
Bật Origin Shield cho workloads có viewers phân tán nhiều region.
🔥
WAF Protection
Gắn WAF web ACL với rate limiting, managed rules. Chặn bot và attacks tại edge.
📝
Security Headers
Dùng Response Headers Policy để thêm HSTS, CSP, X-Content-Type-Options.

Tối ưu Cache Hit Rate

✅ Nên làm
  • Forward ít headers/cookies/query strings nhất có thể
  • Dùng Cache Policy thay vì legacy forwarded values
  • Normalize query string order (a=1&b=2 vs b=2&a=1)
  • Tách static và dynamic content vào behaviors khác nhau
  • Dùng Origin Shield cho multi-region viewers
  • Set TTL phù hợp: dài cho static, ngắn cho dynamic
❌ Tránh làm
  • Forward All headers → mỗi request unique → no cache
  • Forward All cookies cho static content
  • Dùng wildcard invalidation (/*) thường xuyên
  • TTL = 0 cho tất cả content
  • Không bật compression
  • Dùng OAI thay vì OAC cho S3 mới
13 · Tham khảo

AWS CLI Cheat Sheet

Distribution Management

Quản lý Distributions
# Liệt kê tất cả distributions
aws cloudfront list-distributions \
  --query "DistributionList.Items[].{Id:Id,Domain:DomainName,Status:Status,Aliases:Aliases.Items[0]}" \
  --output table

# Xem chi tiết distribution
aws cloudfront get-distribution --id E1234567890

# Xem cấu hình distribution
aws cloudfront get-distribution-config --id E1234567890

# Tạo distribution từ S3 origin (basic)
aws cloudfront create-distribution \
  --origin-domain-name my-bucket.s3.amazonaws.com \
  --default-root-object index.html

# Disable distribution (trước khi xóa)
aws cloudfront get-distribution-config --id E1234567890 --query "ETag" --output text
# Sửa Enabled: false trong config, rồi:
aws cloudfront update-distribution --id E1234567890 \
  --if-match ETAG_VALUE \
  --distribution-config file://disabled-config.json

# Xóa distribution (phải disable trước)
aws cloudfront delete-distribution --id E1234567890 --if-match ETAG_VALUE

Cache Invalidation

Invalidation Commands
# Invalidate file cụ thể
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/index.html" "/about.html"

# Invalidate tất cả files trong thư mục
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/images/*"

# Invalidate TẤT CẢ
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/*"

# Liệt kê invalidations
aws cloudfront list-invalidations --distribution-id E1234567890

# Kiểm tra trạng thái invalidation
aws cloudfront get-invalidation \
  --distribution-id E1234567890 \
  --id I1234567890

OAC Management

Origin Access Control
# Tạo OAC
aws cloudfront create-origin-access-control \
  --origin-access-control-config '{
    "Name": "my-s3-oac",
    "Description": "OAC for S3",
    "SigningProtocol": "sigv4",
    "SigningBehavior": "always",
    "OriginAccessControlOriginType": "s3"
  }'

# Liệt kê OACs
aws cloudfront list-origin-access-controls

# Xem chi tiết OAC
aws cloudfront get-origin-access-control --id E1234567890

CloudFront Functions

CloudFront Functions CLI
# Tạo function
aws cloudfront create-function \
  --name my-url-rewrite \
  --function-config '{
    "Comment": "URL rewrite for SPA",
    "Runtime": "cloudfront-js-2.0"
  }' \
  --function-code fileb://function.js

# Test function
aws cloudfront test-function \
  --name my-url-rewrite \
  --if-match ETAG_VALUE \
  --event-object fileb://test-event.json \
  --stage DEVELOPMENT

# Publish function (DEVELOPMENT → LIVE)
aws cloudfront publish-function \
  --name my-url-rewrite \
  --if-match ETAG_VALUE

# Liệt kê functions
aws cloudfront list-functions

# Xem code function
aws cloudfront get-function --name my-url-rewrite --stage LIVE

Monitoring & Logs

Monitoring Commands
# Xem CloudWatch metrics (requests trong 1 giờ qua)
aws cloudwatch get-metric-statistics \
  --namespace AWS/CloudFront \
  --metric-name Requests \
  --dimensions Name=DistributionId,Value=E1234567890 \
               Name=Region,Value=Global \
  --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%S) \
  --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
  --period 300 \
  --statistics Sum

# Xem cache hit rate
aws cloudwatch get-metric-statistics \
  --namespace AWS/CloudFront \
  --metric-name CacheHitRate \
  --dimensions Name=DistributionId,Value=E1234567890 \
               Name=Region,Value=Global \
  --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%S) \
  --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
  --period 300 \
  --statistics Average

# Tạo CloudWatch alarm cho 5xx errors
aws cloudwatch put-metric-alarm \
  --alarm-name "CloudFront-5xx-High" \
  --namespace AWS/CloudFront \
  --metric-name 5xxErrorRate \
  --dimensions Name=DistributionId,Value=E1234567890 \
               Name=Region,Value=Global \
  --statistic Average \
  --period 300 \
  --threshold 1 \
  --comparison-operator GreaterThanThreshold \
  --evaluation-periods 2 \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:my-alerts

Useful Queries

Athena Query cho CloudFront Logs
-- Tạo table cho CloudFront logs
CREATE EXTERNAL TABLE cloudfront_logs (
  `date` DATE,
  time STRING,
  location STRING,
  bytes BIGINT,
  request_ip STRING,
  method STRING,
  host STRING,
  uri STRING,
  status INT,
  referrer STRING,
  user_agent STRING,
  query_string STRING,
  cookie STRING,
  result_type STRING,
  request_id STRING
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
LOCATION 's3://my-cf-logs-bucket/cf-logs/';

-- Top 10 URIs có nhiều 5xx errors
SELECT uri, COUNT(*) as error_count
FROM cloudfront_logs
WHERE status >= 500 AND `date` >= '2026-04-01'
GROUP BY uri
ORDER BY error_count DESC
LIMIT 10;

-- Cache hit rate theo ngày
SELECT `date`,
  COUNT(CASE WHEN result_type = 'Hit' THEN 1 END) * 100.0 / COUNT(*) as hit_rate
FROM cloudfront_logs
GROUP BY `date`
ORDER BY `date` DESC;
💡 Mẹo CLI
  • Dùng --query với JMESPath để lọc output — tránh output quá dài
  • Dùng --output table cho output dễ đọc, --output json cho scripting
  • Dùng aws cloudfront wait distribution-deployed --id E123 để chờ distribution deploy xong
  • Lưu distribution config ra file: aws cloudfront get-distribution-config --id E123 > config.json

Tổng hợp từ AWS CloudFront Official Documentation và các nguồn uy tín · Cập nhật tháng 4/2026