jpskill.com
🛠️ 開発・MCP コミュニティ

aws-cloudfront

Amazon CloudFrontを設定し、S3やALBを起点としたコンテンツ配信を最適化、キャッシュ設定や無効化、Lambda@Edgeによるエッジでのリクエスト/レスポンス処理を可能にするSkill。

📜 元の英語説明(参考)

Configure Amazon CloudFront for global content delivery. Set up distributions with S3 and ALB origins, define cache behaviors and TTLs, invalidate cached content, and use Lambda@Edge for request/response manipulation at the edge.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Amazon CloudFrontを設定し、S3やALBを起点としたコンテンツ配信を最適化、キャッシュ設定や無効化、Lambda@Edgeによるエッジでのリクエスト/レスポンス処理を可能にするSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o aws-cloudfront.zip https://jpskill.com/download/14663.zip && unzip -o aws-cloudfront.zip && rm aws-cloudfront.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/14663.zip -OutFile "$d\aws-cloudfront.zip"; Expand-Archive "$d\aws-cloudfront.zip" -DestinationPath $d -Force; ri "$d\aws-cloudfront.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して aws-cloudfront.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → aws-cloudfront フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

AWS CloudFront

Amazon CloudFront は、400 以上のエッジロケーションからコンテンツを配信するグローバルな CDN です。静的および動的コンテンツをキャッシュし、SSL を終端処理し、オリジンとして S3、ALB、および API Gateway と統合します。

コアコンセプト

  • Distribution — オリジンとビヘイビアを持つ CloudFront デプロイメント
  • Origin — コンテンツのソース (S3、ALB、カスタム HTTP サーバー)
  • Cache Behavior — URL パターンごとにリクエストを処理する方法のルール
  • Origin Access Control (OAC) — S3 へのアクセスを CloudFront のみに制限
  • Lambda@Edge — リクエスト/レスポンス時にエッジロケーションでコードを実行
  • Invalidation — TTL が期限切れになる前にキャッシュされたコンテンツを削除

Distribution の作成

// dist-config.json — S3 静的サイト + ALB API 用の CloudFront distribution
{
  "CallerReference": "my-app-2024",
  "Comment": "My App CDN",
  "DefaultCacheBehavior": {
    "TargetOriginId": "s3-static",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true,
    "AllowedMethods": ["GET", "HEAD"],
    "CachedMethods": ["GET", "HEAD"]
  },
  "Origins": {
    "Quantity": 2,
    "Items": [
      {
        "Id": "s3-static",
        "DomainName": "my-app-assets.s3.us-east-1.amazonaws.com",
        "OriginAccessControlId": "EABCDEF123456",
        "S3OriginConfig": {"OriginAccessIdentity": ""}
      },
      {
        "Id": "alb-api",
        "DomainName": "app-alb-123456.us-east-1.elb.amazonaws.com",
        "CustomOriginConfig": {
          "HTTPPort": 80,
          "HTTPSPort": 443,
          "OriginProtocolPolicy": "https-only"
        }
      }
    ]
  },
  "CacheBehaviors": {
    "Quantity": 1,
    "Items": [{
      "PathPattern": "/api/*",
      "TargetOriginId": "alb-api",
      "ViewerProtocolPolicy": "https-only",
      "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
      "OriginRequestPolicyId": "216adef6-5c7f-47e4-b989-5492eafa07d3",
      "AllowedMethods": ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"],
      "CachedMethods": ["GET", "HEAD"]
    }]
  },
  "DefaultRootObject": "index.html",
  "Enabled": true,
  "PriceClass": "PriceClass_100",
  "ViewerCertificate": {
    "ACMCertificateArn": "arn:aws:acm:us-east-1:123456789:certificate/abc-123",
    "SSLSupportMethod": "sni-only",
    "MinimumProtocolVersion": "TLSv1.2_2021"
  },
  "Aliases": {"Quantity": 1, "Items": ["app.example.com"]}
}
# distribution を作成
aws cloudfront create-distribution --distribution-config file://dist-config.json

Origin Access Control

# S3 へのアクセスを CloudFront に制限するために OAC を作成
aws cloudfront create-origin-access-control \
  --origin-access-control-config '{
    "Name": "my-app-oac",
    "OriginAccessControlOriginType": "s3",
    "SigningBehavior": "always",
    "SigningProtocol": "sigv4"
  }'
// CloudFront のみを許可する S3 バケットポリシー
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowCloudFront",
    "Effect": "Allow",
    "Principal": {"Service": "cloudfront.amazonaws.com"},
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-app-assets/*",
    "Condition": {
      "StringEquals": {
        "AWS:SourceArn": "arn:aws:cloudfront::123456789:distribution/E1234567890"
      }
    }
  }]
}

キャッシュの無効化

# 特定のパスを無効化
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths '/index.html' '/static/app.js' '/api/config'
# すべてを無効化 (控えめに使用してください — パスごとにコストがかかります)
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths '/*'
# 無効化ステータスを確認
aws cloudfront list-invalidations --distribution-id E1234567890

Lambda@Edge

# lambda-edge/viewer-request.py — セキュリティヘッダーを追加してリダイレクト
def handler(event, context):
    request = event['Records'][0]['cf']['request']
    uri = request['uri']

    # SPA ルーティング: ファイルパス以外の場合は index.html を提供
    if '.' not in uri.split('/')[-1]:
        request['uri'] = '/index.html'

    return request
# lambda-edge/origin-response.py — セキュリティヘッダーを追加
def handler(event, context):
    response = event['Records'][0]['cf']['response']
    headers = response['headers']

    headers['strict-transport-security'] = [{
        'key': 'Strict-Transport-Security',
        'value': 'max-age=63072000; includeSubDomains; preload'
    }]
    headers['x-content-type-options'] = [{
        'key': 'X-Content-Type-Options',
        'value': 'nosniff'
    }]
    headers['x-frame-options'] = [{
        'key': 'X-Frame-Options',
        'value': 'DENY'
    }]

    return response

カスタムエラーページ

# カスタムエラーレスポンスを設定 (SPA フォールバック)
aws cloudfront update-distribution \
  --id E1234567890 \
  --if-match ETAG123 \
  --distribution-config '...' # CustomErrorResponses を含める:
// SPA ルーティング用のカスタムエラーレスポンス
{
  "CustomErrorResponses": {
    "Quantity": 2,
    "Items": [
      {"ErrorCode": 403, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10},
      {"ErrorCode": 404, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10}
    ]
  }
}

モニタリング

# distribution の詳細を取得
aws cloudfront get-distribution --id E1234567890 \
  --query 'Distribution.[DomainName,Status,DistributionConfig.Enabled]'
# リアルタイムログを有効にする
aws cloudfront create-realtime-log-config \
  --name app-realtime-logs \
  --sampling-rate 100 \
  --fields "timestamp" "c-ip" "sc-status" "cs-uri-stem" "time-taken" \
  --end-points '[{"StreamType":"Kinesis","KinesisStreamConfig":{"RoleARN":"arn:aws:iam::123456789:role/cf-realtime-logs","StreamARN":"arn:aws:kinesis:us-east-1:123456789:stream/cf-logs"}}]'

ベストプラクティス

  • S3 オリジンには、従来の OAI ではなく Origin Access Control (OAC) を使用します。
  • テキストベースのアセット (HTML、CSS、JS、JSON) に対して圧縮を有効にします。
  • マネージドキャッシュポリシーを使用します。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

AWS CloudFront

Amazon CloudFront is a global CDN that delivers content from 400+ edge locations. It caches static and dynamic content, terminates SSL, and integrates with S3, ALB, and API Gateway as origins.

Core Concepts

  • Distribution — a CloudFront deployment with origins and behaviors
  • Origin — the source of content (S3, ALB, custom HTTP server)
  • Cache Behavior — rules for how requests are handled per URL pattern
  • Origin Access Control (OAC) — restricts S3 access to CloudFront only
  • Lambda@Edge — run code at edge locations on request/response
  • Invalidation — remove cached content before TTL expires

Creating a Distribution

// dist-config.json — CloudFront distribution for S3 static site + ALB API
{
  "CallerReference": "my-app-2024",
  "Comment": "My App CDN",
  "DefaultCacheBehavior": {
    "TargetOriginId": "s3-static",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true,
    "AllowedMethods": ["GET", "HEAD"],
    "CachedMethods": ["GET", "HEAD"]
  },
  "Origins": {
    "Quantity": 2,
    "Items": [
      {
        "Id": "s3-static",
        "DomainName": "my-app-assets.s3.us-east-1.amazonaws.com",
        "OriginAccessControlId": "EABCDEF123456",
        "S3OriginConfig": {"OriginAccessIdentity": ""}
      },
      {
        "Id": "alb-api",
        "DomainName": "app-alb-123456.us-east-1.elb.amazonaws.com",
        "CustomOriginConfig": {
          "HTTPPort": 80,
          "HTTPSPort": 443,
          "OriginProtocolPolicy": "https-only"
        }
      }
    ]
  },
  "CacheBehaviors": {
    "Quantity": 1,
    "Items": [{
      "PathPattern": "/api/*",
      "TargetOriginId": "alb-api",
      "ViewerProtocolPolicy": "https-only",
      "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
      "OriginRequestPolicyId": "216adef6-5c7f-47e4-b989-5492eafa07d3",
      "AllowedMethods": ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"],
      "CachedMethods": ["GET", "HEAD"]
    }]
  },
  "DefaultRootObject": "index.html",
  "Enabled": true,
  "PriceClass": "PriceClass_100",
  "ViewerCertificate": {
    "ACMCertificateArn": "arn:aws:acm:us-east-1:123456789:certificate/abc-123",
    "SSLSupportMethod": "sni-only",
    "MinimumProtocolVersion": "TLSv1.2_2021"
  },
  "Aliases": {"Quantity": 1, "Items": ["app.example.com"]}
}
# Create distribution
aws cloudfront create-distribution --distribution-config file://dist-config.json

Origin Access Control

# Create OAC to restrict S3 access to CloudFront
aws cloudfront create-origin-access-control \
  --origin-access-control-config '{
    "Name": "my-app-oac",
    "OriginAccessControlOriginType": "s3",
    "SigningBehavior": "always",
    "SigningProtocol": "sigv4"
  }'
// S3 bucket policy allowing only CloudFront
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowCloudFront",
    "Effect": "Allow",
    "Principal": {"Service": "cloudfront.amazonaws.com"},
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-app-assets/*",
    "Condition": {
      "StringEquals": {
        "AWS:SourceArn": "arn:aws:cloudfront::123456789:distribution/E1234567890"
      }
    }
  }]
}

Cache Invalidation

# Invalidate specific paths
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths '/index.html' '/static/app.js' '/api/config'
# Invalidate everything (use sparingly — costs per path)
aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths '/*'
# Check invalidation status
aws cloudfront list-invalidations --distribution-id E1234567890

Lambda@Edge

# lambda-edge/viewer-request.py — add security headers and redirect
def handler(event, context):
    request = event['Records'][0]['cf']['request']
    uri = request['uri']

    # SPA routing: serve index.html for non-file paths
    if '.' not in uri.split('/')[-1]:
        request['uri'] = '/index.html'

    return request
# lambda-edge/origin-response.py — add security headers
def handler(event, context):
    response = event['Records'][0]['cf']['response']
    headers = response['headers']

    headers['strict-transport-security'] = [{
        'key': 'Strict-Transport-Security',
        'value': 'max-age=63072000; includeSubDomains; preload'
    }]
    headers['x-content-type-options'] = [{
        'key': 'X-Content-Type-Options',
        'value': 'nosniff'
    }]
    headers['x-frame-options'] = [{
        'key': 'X-Frame-Options',
        'value': 'DENY'
    }]

    return response

Custom Error Pages

# Configure custom error responses (SPA fallback)
aws cloudfront update-distribution \
  --id E1234567890 \
  --if-match ETAG123 \
  --distribution-config '...' # Include CustomErrorResponses:
// Custom error responses for SPA routing
{
  "CustomErrorResponses": {
    "Quantity": 2,
    "Items": [
      {"ErrorCode": 403, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10},
      {"ErrorCode": 404, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10}
    ]
  }
}

Monitoring

# Get distribution details
aws cloudfront get-distribution --id E1234567890 \
  --query 'Distribution.[DomainName,Status,DistributionConfig.Enabled]'
# Enable real-time logs
aws cloudfront create-realtime-log-config \
  --name app-realtime-logs \
  --sampling-rate 100 \
  --fields "timestamp" "c-ip" "sc-status" "cs-uri-stem" "time-taken" \
  --end-points '[{"StreamType":"Kinesis","KinesisStreamConfig":{"RoleARN":"arn:aws:iam::123456789:role/cf-realtime-logs","StreamARN":"arn:aws:kinesis:us-east-1:123456789:stream/cf-logs"}}]'

Best Practices

  • Use Origin Access Control (not legacy OAI) for S3 origins
  • Enable compression for text-based assets (HTML, CSS, JS, JSON)
  • Use managed cache policies instead of custom forwarding settings
  • Invalidate sparingly — use versioned filenames (app.v2.js) instead
  • Set appropriate TTLs: long for static assets, short for dynamic content
  • Use Lambda@Edge for SPA routing, A/B testing, and auth at the edge
  • Enable HTTPS everywhere with ACM certificates (must be in us-east-1)