ระดับ 2 · บทที่ 4/5

เว็บแรกขึ้นออนไลน์ 2 แบบ — S3 + CloudFront (OAC) และ Workers static assets

⏱ 60 นาทีลองในAWS Console ↗Cloudflare ↗
ข้อมูลบางส่วนอาจเปลี่ยน — ตรวจสอบก่อนใช้

บทนี้มีข้อมูลที่เปลี่ยนบ่อย (ฟีเจอร์ ราคา ชื่อเมนู) ตรวจกับเว็บทางการก่อนนำไปใช้

เป้าหมาย

เอาเว็บนิ่งหน้าเดียวกันขึ้นออนไลน์ด้วย HTTPS สองวิธี แล้วเทียบกันเอง: (A) S3 + CloudFront ที่ bucket เป็น private และให้ CloudFront อ่านผ่าน Origin Access Control (OAC) (B) Cloudflare Workers static assets ด้วย wrangler deploy คำสั่งเดียว — และลบทั้งหมดทิ้งได้เมื่อจบ

เตรียมไฟล์เว็บ (ใช้ร่วมกันทั้งสองวิธี)

mkdir -p ~/cloud-ladder/site && cd ~/cloud-ladder/site
cat > index.html <<'EOF'
<!doctype html>
<html lang="th"><head><meta charset="utf-8"><title>Cloud Ladder</title>
<link rel="stylesheet" href="/style.css"></head>
<body><h1>เว็บแรกของฉันบนคลาวด์</h1><p>ถ้าเห็นหน้านี้ผ่าน HTTPS แปลว่าสำเร็จ</p></body></html>
EOF
echo 'body{font-family:sans-serif;max-width:40rem;margin:4rem auto}' > style.css
cat > 404.html <<'EOF'
<!doctype html><html lang="th"><head><meta charset="utf-8"><title>ไม่พบหน้า</title></head>
<body><h1>404 — ไม่พบหน้านี้</h1></body></html>
EOF
ls

ผลที่ควรเห็น: 404.html index.html style.css

วิธี A — S3 + CloudFront + OAC

ทำไมต้องซับซ้อนกว่าการเปิด bucket เป็น public:

แบบ ข้อเสีย
S3 static website hosting (public bucket) ไม่มี HTTPS ในตัว, bucket ต้องเปิด public, คนอ่านไฟล์ตรงจาก S3 ได้
S3 private + CloudFront + OAC ✅ ได้ HTTPS, แคชที่ edge, bucket ไม่ public — อ่านได้เฉพาะผ่าน distribution ของเรา
ผู้ใช้ ──HTTPS──► CloudFront (edge) ──เซ็นคำขอด้วย OAC (SigV4)──► S3 bucket (private, Block Public Access เปิดอยู่)

OAC = "บัตรผ่าน" ที่ CloudFront ใช้เซ็นคำขอ · bucket policy = "ป้ายหน้าประตู" ที่บอกว่ายอมให้เฉพาะ distribution ID นี้เข้า

⚠️ อาจมีค่าใช้จ่าย: S3 (พื้นที่+request) และ CloudFront (data transfer+request) — เว็บทดลองขนาดนี้ปกติอยู่ในเครดิต/โควตาฟรี แต่ให้ทำ clean-up ท้ายบทเสมอ ⚠️ ต้องตรวจสอบ: CloudFront มีทั้งแบบจ่ายตามใช้และ flat-rate pricing plans (มีแผน $0) ซึ่ง console อาจเสนอให้เลือก — distribution ที่สมัครแผน flat-rate ต้องยกเลิกแผนก่อนจึงลบได้ · lab นี้สร้างด้วย CLI ซึ่งเป็นแบบจ่ายตามใช้

ขั้น A1 — สร้าง bucket แบบ private และอัปโหลด

mkdir -p ~/cloud-ladder/aws-lab && cd ~/cloud-ladder/aws-lab   # ไฟล์ JSON ของ lab อยู่ที่นี่ ไม่ปนกับไฟล์เว็บ
export AWS_PROFILE=learn AWS_REGION=ap-southeast-1
aws sso login                                                  # ถ้า session จากบท 03 หมดอายุแล้ว
aws sts get-caller-identity --query Arn --output text          # ตรวจบัญชีก่อนเสมอ
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
BUCKET="cloud-ladder-site-$ACCOUNT_ID"                           # ชื่อ bucket ต้องไม่ซ้ำทั้งโลก

aws s3api create-bucket --bucket "$BUCKET" --region "$AWS_REGION" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"
aws s3api put-bucket-tagging --bucket "$BUCKET" \
  --tagging 'TagSet=[{Key=project,Value=cloud-ladder}]'
aws s3api get-public-access-block --bucket "$BUCKET" \
  --query 'PublicAccessBlockConfiguration' --output text
aws s3 sync ~/cloud-ladder/site "s3://$BUCKET/" --delete

ผลที่ควรเห็น:

{ "Location": "http://cloud-ladder-site-111122223333.s3.amazonaws.com/" }
True	True	True	True
upload: ../site/404.html to s3://cloud-ladder-site-111122223333/404.html
upload: ../site/index.html to s3://cloud-ladder-site-111122223333/index.html
upload: ../site/style.css to s3://cloud-ladder-site-111122223333/style.css

→ True True True True = Block Public Access เปิดครบ (ค่าเริ่มต้นของ bucket ใหม่) ห้ามปิด

ขั้น A2 — สร้าง OAC และ distribution

OAC_ID=$(aws cloudfront create-origin-access-control \
  --origin-access-control-config Name=cloud-ladder-oac,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3 \
  --query OriginAccessControl.Id --output text)
echo "OAC: $OAC_ID"

cat > dist.json <<EOF
{
  "CallerReference": "cloud-ladder-$(date +%s)",
  "Comment": "cloud-ladder level 2",
  "Enabled": true,
  "DefaultRootObject": "index.html",
  "Origins": { "Quantity": 1, "Items": [ {
    "Id": "s3-site",
    "DomainName": "$BUCKET.s3.$AWS_REGION.amazonaws.com",
    "S3OriginConfig": { "OriginAccessIdentity": "" },
    "OriginAccessControlId": "$OAC_ID"
  } ] },
  "DefaultCacheBehavior": {
    "TargetOriginId": "s3-site",
    "ViewerProtocolPolicy": "redirect-to-https",
    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
    "Compress": true
  },
  "CustomErrorResponses": { "Quantity": 1, "Items": [ {
    "ErrorCode": 403, "ResponsePagePath": "/404.html", "ResponseCode": "404", "ErrorCachingMinTTL": 60
  } ] }
}
EOF
read DIST_ID CF_DOMAIN < <(aws cloudfront create-distribution --distribution-config file://dist.json \
  --query 'Distribution.[Id,DomainName]' --output text)
echo "DIST_ID=$DIST_ID  https://$CF_DOMAIN"
echo "BUCKET=$BUCKET OAC_ID=$OAC_ID DIST_ID=$DIST_ID CF_DOMAIN=$CF_DOMAIN ACCOUNT_ID=$ACCOUNT_ID" > ids.txt
  • 658327ea-... = managed cache policy CachingOptimized
  • CustomErrorResponses แปลง 403 → 404.html: S3 ตอบ 403 (ไม่ใช่ 404) เมื่อขอไฟล์ที่ไม่มี เพราะเราไม่ได้ให้สิทธิ์ s3:ListBucket
  • บรรทัดสุดท้ายบันทึก ID ทั้งหมดลง ids.txt — ต้องใช้ตอนลบ · ถ้าปิดเทอร์มินัลแล้วตัวแปรหาย ให้ cd ~/cloud-ladder/aws-lab && export AWS_PROFILE=learn AWS_REGION=ap-southeast-1 && source ids.txt
  • ไฟล์ JSON อยู่ใน aws-lab/ ไม่ใช่ site/ — ถ้าวางปนกับไฟล์เว็บ s3 sync/wrangler deploy จะอัปโหลดมันขึ้นไปให้ทุกคนอ่านได้

ขั้น A3 — bucket policy ให้เฉพาะ distribution นี้อ่านได้

cat > bucket-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [ {
    "Sid": "AllowCloudFrontServicePrincipalReadOnly",
    "Effect": "Allow",
    "Principal": { "Service": "cloudfront.amazonaws.com" },
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::$BUCKET/*",
    "Condition": { "StringEquals": {
      "AWS:SourceArn": "arn:aws:cloudfront::$ACCOUNT_ID:distribution/$DIST_ID"
    } }
  } ]
}
EOF
aws s3api put-bucket-policy --bucket "$BUCKET" --policy file://bucket-policy.json
aws cloudfront wait distribution-deployed --id "$DIST_ID" && echo "deployed"

→ wait อาจใช้หลายนาที (กระจาย config ไปทุก edge)

ขั้น A4 — ทดสอบ

curl -sI "https://$CF_DOMAIN/" | grep -iE '^(HTTP|x-cache|content-type)'
curl -s -o /dev/null -w "%{http_code}\n" "https://$CF_DOMAIN/nope"
curl -s -o /dev/null -w "%{http_code}\n" "https://$BUCKET.s3.$AWS_REGION.amazonaws.com/index.html"
curl -sI "http://$CF_DOMAIN/" | grep -iE '^(HTTP|location)'

ผลที่ควรเห็น:

HTTP/2 200
content-type: text/html
x-cache: Miss from cloudfront        ← รันซ้ำจะเป็น Hit from cloudfront
404
403                                   ← อ่านตรงจาก S3 ไม่ได้ = bucket ปลอดภัย
HTTP/1.1 301 Moved Permanently
Location: https://d111111abcdef8.cloudfront.net/

อัปเดตเว็บ: แก้ไฟล์ → aws s3 sync ~/cloud-ladder/site "s3://$BUCKET/" --delete → ล้างแคช aws cloudfront create-invalidation --distribution-id "$DIST_ID" --paths "/*" (invalidation จำนวนหนึ่งต่อเดือนฟรี เกินคิดเงิน — ⚠️ ต้องตรวจสอบโควตาในหน้า pricing)

วิธี B — Cloudflare Workers static assets

Workers ไม่ได้มีไว้แค่รันโค้ด — ถ้า config มีแค่ assets (ไม่มี main) จะเป็นเว็บนิ่งล้วน request ไปที่ static assets ฟรีไม่จำกัด (ขีดจำกัด: 20,000 ไฟล์ต่อเวอร์ชันบน Free, 25 MiB ต่อไฟล์)

Cloudflare Pages ยังใช้ได้ แต่ Cloudflare แนะนำให้โปรเจกต์ใหม่ใช้ Workers + static assets ซึ่งต่อยอดเป็น API/SSR ในโปรเจกต์เดียวได้ — หลักสูตรนี้จึงใช้ Workers

cd ~/cloud-ladder/hello-edge                       # โปรเจกต์จากบท 03 (มี wrangler ใน devDependencies)
rm -rf public && cp -r ~/cloud-ladder/site public
cat > wrangler.jsonc <<'EOF'
{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "hello-edge",
  "compatibility_date": "2026-09-01",
  "assets": {
    "directory": "./public",
    "not_found_handling": "404-page"
  }
}
EOF
npx wrangler deploy

ผลที่ควรเห็น (โดยประมาณ):

🌀 Building list of assets...
🌀 Starting asset upload...
Uploaded 3 of 3 assets
✨ Success! Uploaded 3 files
Uploaded hello-edge (x.xx sec)
Deployed hello-edge triggers (x.xx sec)
  https://hello-edge.[subdomain-ของคุณ].workers.dev
Current Version ID: 01234567-89ab-cdef-0123-456789abcdef
  • ครั้งแรก wrangler อาจถามให้ตั้ง workers.dev subdomain ของบัญชี
  • not_found_handling: "404-page" → ไม่พบไฟล์จะส่ง 404.html ที่ใกล้ที่สุด (เว็บแบบ SPA ใช้ "single-page-application")
URL="https://hello-edge.[subdomain-ของคุณ].workers.dev"
curl -sI "$URL/" | grep -iE '^(HTTP|server|content-type)'
curl -s -o /dev/null -w "%{http_code}\n" "$URL/nope"

ผลที่ควรเห็น:

HTTP/2 200
server: cloudflare
content-type: text/html
404

อัปเดตเว็บ: แก้ไฟล์ใน public/ → npx wrangler deploy (ไม่ต้องล้างแคชเอง) · ย้อนเวอร์ชัน: npx wrangler rollback

เทียบกันหลังทำจริง

S3 + CloudFront + OAC Workers static assets
จำนวนคำสั่ง ~10 + JSON 2 ไฟล์ wrangler deploy
เวลาจนออนไลน์ หลายนาที (รอ deploy ทุก edge) ไม่กี่วินาที
HTTPS ✅ (*.cloudfront.net, โดเมนเองต้องใช้ ACM ที่ us-east-1) ✅ (*.workers.dev, โดเมนใน Cloudflare ผูกได้ทันที)
ล้างแคชหลังอัปเดต ต้อง invalidation อัตโนมัติ
ค่าใช้จ่าย จ่ายตามใช้ (พื้นที่ + transfer + request) request ไป static assets ฟรี
ควบคุมละเอียด สูงมาก (cache behavior, Lambda@Edge, WAF, log) ปานกลาง (_headers, _redirects, เพิ่ม Worker script)
เหมาะเมื่อ ระบบอยู่บน AWS อยู่แล้ว, ต้องการ IAM/compliance เว็บใหม่, ทีมเล็ก, อยากเร็วและฟรี

Clean-up (ทำเมื่อเทียบเสร็จ — ถ้าจะทำบท 05 ต่อ ให้ทำในบท 05)

# --- Cloudflare ---
cd ~/cloud-ladder/hello-edge && npx wrangler delete

# --- AWS: ปิด distribution → รอ → ลบ → ลบ OAC → ลบ bucket ---
cd ~/cloud-ladder/aws-lab
export AWS_PROFILE=learn AWS_REGION=ap-southeast-1
source ids.txt                                    # โหลด DIST_ID, OAC_ID, BUCKET ที่บันทึกไว้ในขั้น A2
aws sts get-caller-identity --query Arn --output text   # ตรวจบัญชีก่อนลบ
ETAG=$(aws cloudfront get-distribution-config --id "$DIST_ID" --query ETag --output text)
aws cloudfront get-distribution-config --id "$DIST_ID" --query DistributionConfig > current.json
python3 -c "import json;c=json.load(open('current.json'));c['Enabled']=False;json.dump(c,open('disabled.json','w'))"
aws cloudfront update-distribution --id "$DIST_ID" --distribution-config file://disabled.json --if-match "$ETAG" >/dev/null
aws cloudfront wait distribution-deployed --id "$DIST_ID"
ETAG=$(aws cloudfront get-distribution --id "$DIST_ID" --query ETag --output text)
aws cloudfront delete-distribution --id "$DIST_ID" --if-match "$ETAG"
OAC_ETAG=$(aws cloudfront get-origin-access-control --id "$OAC_ID" --query ETag --output text)
aws cloudfront delete-origin-access-control --id "$OAC_ID" --if-match "$OAC_ETAG"
aws s3 rb "s3://$BUCKET" --force
rm -f dist.json bucket-policy.json current.json disabled.json ids.txt

→ ลบ distribution ก่อน bucket เสมอ (ตามคำแนะนำของ AWS) · ถ้าลืม DIST_ID: aws cloudfront list-distributions --query 'DistributionList.Items[].[Id,Comment]' --output text

กับดักที่เจอบ่อย

อาการ สาเหตุ / แก้
CloudFront ตอบ 403 ทุกหน้า bucket policy ยังไม่ใส่/ใส่ distribution ID ผิด หรือ origin ใช้ endpoint แบบ s3-website- (OAC ใช้ไม่ได้)
หน้าแรกได้ 403 แต่ /index.html ได้ 200 ลืม DefaultRootObject: index.html
แก้ไฟล์แล้ว CloudFront ยังเสิร์ฟของเก่า ยังไม่ invalidation หรือรอ TTL ของแคช
delete-distribution ได้ DistributionNotDisabled ต้อง disable และรอ deployed ก่อน
InvalidIfMatchVersion ETag เก่า — ดึง ETag ใหม่หลังทุกการแก้
wrangler deploy บอก Missing entry-point config ไม่มี assets.directory หรือพิมพ์ path ผิด
เผลอ deploy node_modules/.env ขึ้นไป ชี้ assets.directory ไปโฟลเดอร์ที่มีเฉพาะไฟล์เว็บเท่านั้น (เช่น public/)

สรุปจำง่าย

AWS: bucket private + Block Public Access + OAC + bucket policy ผูก AWS:SourceArn = ปลอดภัย · 403 จาก S3 มักแปลว่า "ไม่มีไฟล์" หรือ "ไม่มีสิทธิ์" — Cloudflare: assets.directory + wrangler deploy จบ — ลบ distribution ก่อน bucket และ wrangler delete เมื่อเลิกใช้