AWS CloudFront 邊緣快取優化

AWS CloudFront Edge Cache Optimization

CloudFront 概述

Amazon CloudFront 是 AWS 提供的內容傳遞網路 (CDN) 服務,透過全球分佈的邊緣節點快取內容,大幅縮短使用者存取延遲並降低原始伺服器負載。CloudFront 與 AWS 服務如 S3、EC2、Lambda@Edge 深度整合,提供安全、高效能的內容傳遞解決方案。

主要優勢

  • 全球覆蓋:超過 450 個邊緣節點遍佈全球
  • 低延遲:就近服務使用者請求
  • 安全性:整合 AWS Shield、WAF 防護
  • 成本效益:減少原始伺服器流量支出

查看 CloudFront 分發清單

1
2
3
4
5
# 列出所有 CloudFront 分發
aws cloudfront list-distributions --query 'DistributionList.Items[*].[Id,DomainName,Status]' --output table

# 取得特定分發的詳細資訊
aws cloudfront get-distribution --id E1EXAMPLE12345

快取行為設定

快取行為 (Cache Behavior) 決定 CloudFront 如何處理不同路徑的請求。透過設定多個快取行為,可以針對不同類型的內容套用最佳化的快取策略。

建立快取行為配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 建立快取行為設定檔
cat > cache-behavior.json << 'EOF'
{
    "PathPattern": "/static/*",
    "TargetOriginId": "myS3Origin",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true,
    "AllowedMethods": {
        "Quantity": 2,
        "Items": ["GET", "HEAD"]
    }
}
EOF

TTL 設定

TTL (Time To Live) 控制內容在邊緣節點的快取時間。合理設定 TTL 可以平衡快取效益與內容新鮮度。

TTL 層級說明

設定層級說明
Minimum TTL最小快取時間,即使 Origin 回傳較短的 TTL
Maximum TTL最大快取時間上限
Default TTL當 Origin 未指定 Cache-Control 時使用

設定自訂 TTL

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 建立自訂快取政策
aws cloudfront create-cache-policy --cache-policy-config '{
    "Name": "CustomCachePolicy",
    "MinTTL": 1,
    "MaxTTL": 31536000,
    "DefaultTTL": 86400,
    "ParametersInCacheKeyAndForwardedToOrigin": {
        "EnableAcceptEncodingGzip": true,
        "EnableAcceptEncodingBrotli": true,
        "HeadersConfig": {
            "HeaderBehavior": "none"
        },
        "CookiesConfig": {
            "CookieBehavior": "none"
        },
        "QueryStringsConfig": {
            "QueryStringBehavior": "none"
        }
    }
}'

Cache Policy

Cache Policy 定義快取鍵的組成元素,決定哪些請求參數會影響快取命中判斷。

常用的受管理快取政策

政策名稱用途
CachingOptimized最大化快取命中率
CachingDisabled不快取,直接轉發至 Origin
CachingOptimizedForUncompressedObjects不壓縮的靜態內容

查看與套用快取政策

1
2
3
4
5
# 列出所有快取政策
aws cloudfront list-cache-policies --type managed --query 'CachePolicyList.Items[*].[CachePolicy.Id,CachePolicy.CachePolicyConfig.Name]' --output table

# 取得特定快取政策詳細資訊
aws cloudfront get-cache-policy --id 658327ea-f89d-4fab-a63d-7e88639e58f6

Origin Request Policy

Origin Request Policy 控制轉發至 Origin 的請求內容,與 Cache Policy 分離後可以更靈活地設定。

建立 Origin Request Policy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 建立自訂 Origin Request Policy
aws cloudfront create-origin-request-policy --origin-request-policy-config '{
    "Name": "CustomOriginRequestPolicy",
    "HeadersConfig": {
        "HeaderBehavior": "whitelist",
        "Headers": {
            "Quantity": 2,
            "Items": ["Accept-Language", "User-Agent"]
        }
    },
    "CookiesConfig": {
        "CookieBehavior": "none"
    },
    "QueryStringsConfig": {
        "QueryStringBehavior": "all"
    }
}'

# 列出所有 Origin Request Policy
aws cloudfront list-origin-request-policies --type managed

快取失效

當需要立即更新快取內容時,可以建立快取失效請求。請注意,頻繁的失效操作會產生額外費用。

建立快取失效

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 失效特定路徑
aws cloudfront create-invalidation \
    --distribution-id E1EXAMPLE12345 \
    --paths "/images/logo.png" "/css/style.css"

# 失效整個目錄
aws cloudfront create-invalidation \
    --distribution-id E1EXAMPLE12345 \
    --paths "/static/*"

# 失效所有內容(謹慎使用)
aws cloudfront create-invalidation \
    --distribution-id E1EXAMPLE12345 \
    --paths "/*"

# 查看失效請求狀態
aws cloudfront get-invalidation \
    --distribution-id E1EXAMPLE12345 \
    --id I1EXAMPLE12345

最佳實踐

  • 使用版本化的檔案名稱(如 style.v2.css)減少失效需求
  • 批次處理多個路徑的失效請求
  • 每月前 1,000 個路徑免費

壓縮設定

CloudFront 支援 Gzip 和 Brotli 壓縮,可大幅減少傳輸資料量。

啟用壓縮

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 在快取行為中啟用壓縮
# 確保 Cache Policy 包含 Accept-Encoding 標頭

# 建立支援壓縮的快取政策
aws cloudfront create-cache-policy --cache-policy-config '{
    "Name": "CompressionEnabledPolicy",
    "MinTTL": 1,
    "MaxTTL": 31536000,
    "DefaultTTL": 86400,
    "ParametersInCacheKeyAndForwardedToOrigin": {
        "EnableAcceptEncodingGzip": true,
        "EnableAcceptEncodingBrotli": true,
        "HeadersConfig": {
            "HeaderBehavior": "none"
        },
        "CookiesConfig": {
            "CookieBehavior": "none"
        },
        "QueryStringsConfig": {
            "QueryStringBehavior": "none"
        }
    }
}'

壓縮支援的內容類型

CloudFront 自動壓縮以下 MIME 類型:

  • text/html, text/css, text/javascript
  • application/javascript, application/json
  • application/xml, image/svg+xml

Origin Shield

Origin Shield 是額外的快取層,位於區域邊緣快取與 Origin 之間,可進一步降低 Origin 負載。

啟用 Origin Shield

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 更新分發設定以啟用 Origin Shield
cat > origin-shield-config.json << 'EOF'
{
    "OriginShield": {
        "Enabled": true,
        "OriginShieldRegion": "ap-northeast-1"
    }
}
EOF

# 選擇最靠近 Origin 的區域作為 Origin Shield 區域
# 常用區域:
# - us-east-1 (維吉尼亞)
# - eu-west-1 (愛爾蘭)
# - ap-northeast-1 (東京)

Origin Shield 適用場景

  • 全球流量分佈廣泛
  • Origin 容量有限
  • 動態打包或即時轉碼服務

監控快取命中率

監控快取效能是持續優化的關鍵。CloudFront 提供多種監控方式。

使用 CloudWatch 監控

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 取得快取命中率指標
aws cloudwatch get-metric-statistics \
    --namespace AWS/CloudFront \
    --metric-name CacheHitRate \
    --dimensions Name=DistributionId,Value=E1EXAMPLE12345 \
    --start-time 2024-12-21T00:00:00Z \
    --end-time 2024-12-22T00:00:00Z \
    --period 3600 \
    --statistics Average

# 取得請求數量
aws cloudwatch get-metric-statistics \
    --namespace AWS/CloudFront \
    --metric-name Requests \
    --dimensions Name=DistributionId,Value=E1EXAMPLE12345 \
    --start-time 2024-12-21T00:00:00Z \
    --end-time 2024-12-22T00:00:00Z \
    --period 3600 \
    --statistics Sum

啟用標準日誌

1
2
3
4
5
6
7
# 設定 S3 儲存桶接收存取日誌
aws cloudfront update-distribution \
    --id E1EXAMPLE12345 \
    --distribution-config file://distribution-config-with-logging.json

# 日誌分析可使用 Athena 查詢
# 建立 Athena 表格來分析快取狀態

關鍵指標解讀

指標說明目標值
CacheHitRate快取命中率> 80%
OriginLatencyOrigin 回應時間< 500ms
4xxErrorRate4xx 錯誤率< 1%
5xxErrorRate5xx 錯誤率< 0.1%

參考資料

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy