เป้าหมาย
ย้ายงาน "จุกจิกที่ขอบ" ออกจากโค้ดไปไว้ที่ Cloudflare: redirect www/โดเมนเก่า, เพิ่ม security header, rewrite path โดยผู้ใช้ไม่เห็น, ส่งบาง path ไป origin อื่น — เลือกชนิด Rule ให้ถูกและทดสอบได้ด้วย curl
เลือกชนิด Rule
| อยากทำ | ใช้ | ผู้ใช้เห็น URL เปลี่ยน? |
|---|---|---|
www.example.com → example.com, /old → /new (มีเงื่อนไข) |
Single Redirects (Redirect Rules) | ✅ ได้ 301/302 |
| redirect เป็นรายการยาว (ย้ายเว็บ 500 URL) | Bulk Redirects (list + rule ระดับบัญชี) | ✅ |
/blog/123 → ส่งไป origin เป็น /posts?id=123 |
Transform Rules › URL Rewrite | ❌ เปลี่ยนเงียบๆ |
| เพิ่ม/ลบ header ขาไป origin หรือขากลับผู้ใช้ | Transform Rules › Request/Response Header | ❌ |
เปลี่ยนพอร์ต origin (ทุกแพลน) · /api/* ไป origin อื่น / เปลี่ยน Host header (Enterprise) |
Origin Rules | ❌ |
| เปลี่ยนการตั้งค่าเฉพาะบาง path (เช่น SSL mode, ปิด Rocket Loader) | Configuration Rules | ❌ |
| logic ซับซ้อน มี state | Workers (ระดับ 4c) | แล้วแต่โค้ด |
Page Rules เป็นของรุ่นเก่า — งานใหม่ใช้ Rules ชนิดข้างบนแทน
ภาษาของเงื่อนไข (Rules language)
เหมือน Wireshark filter ใช้ field กับ operator
(http.host eq "www.example.com")
(starts_with(http.request.uri.path, "/blog/"))
(http.request.uri.path in {"/old-pricing" "/pricing-2024"})
(http.request.uri.path wildcard "/docs/*" and not http.cookie contains "beta=1")ค่าปลายทางแบบ dynamic ใช้ฟังก์ชัน เช่น
concat("https://example.com", http.request.uri.path)
wildcard_replace(http.request.full_uri, "https://www.example.com/*", "https://example.com/${1}")- Free ใช้ wildcard ได้ แต่ regex ไม่ได้ (
matchesต้องแพลนสูงกว่า) - Single Redirects: Free 10 rules/โซน · Bulk Redirects: Free 5 lists, รวม 10,000 URL ต่อบัญชี · Transform Rules: Free รวม 10 (URL rewrite + request/response header) · Origin Rules: Free 10
Redirect: 301 หรือ 302
| 301 / 308 | 302 / 307 | |
|---|---|---|
| เบราว์เซอร์/Google จำ | จำถาวร (cache นาน) | ไม่จำ |
| ใช้กับ | ย้ายถาวร, www → apex | แคมเปญชั่วคราว, ทดสอบ |
| 307/308 | รักษา method + body (POST ยังเป็น POST) |
⚠️ ทดสอบด้วย 302 ก่อนเสมอ — 301 ผิดแล้วเบราว์เซอร์ผู้ใช้จำไปอีกนาน แก้ที่ server ไม่หาย
Transform Rules — header ความปลอดภัยแบบไม่ต้องแตะโค้ด
Response header ที่ควรมีแทบทุกเว็บ
| Header | ค่า |
|---|---|
X-Content-Type-Options |
nosniff |
Referrer-Policy |
strict-origin-when-cross-origin |
X-Frame-Options |
DENY (หรือใช้ CSP frame-ancestors) |
Permissions-Policy |
camera=(), microphone=(), geolocation=() |
ลบ X-Powered-By ของ origin |
ลดข้อมูลให้ผู้โจมตี (header server และ cf-* แก้/ลบด้วย Transform Rule ไม่ได้) |
Origin Rules — หลาย backend ใต้โดเมนเดียว
example.com/api/* → origin api-backend.example.com (เช่น ALB) โดยเปลี่ยน DNS record + Host header ให้ตรงกับ cert ของ origin · ที่เหลือ → origin เดิม — ทางที่ถูกกว่า Load Balancer สำหรับกรณีง่าย
- ⚠️ override DNS record / Host header / SNI ใช้ได้เฉพาะ Enterprise — Free/Pro/Business ใช้ Origin Rules ได้แค่เปลี่ยน พอร์ต · แพลนอื่นทำงานนี้ด้วย Worker บน route
example.com/api/*ที่fetch()ไป backend (ระดับ 4c)
ลองเลย 🧪
ใช้ตัวแปร CLOUDFLARE_API_TOKEN, ZONE, ZONE_ID จากบท 01 · token ต้องมีสิทธิ์แก้ Single Redirect และ Transform Rules ของโซน + DNS › Edit (ชื่อสิทธิ์ดูในหน้าสร้าง API token — ถ้าได้ error 10000/403 แปลว่าสิทธิ์ไม่พอ)
⚠️ คำสั่ง PUT .../entrypoint แทนที่ทุก rule ใน phase นั้น — ถ้าโซนมีกฎอยู่แล้ว ให้ทำในแดชบอร์ด (Rules › Overview) แทน
ทดลอง A — redirect www → apex (ทดสอบด้วย 302)
# www ต้องมี DNS record แบบ proxied ไม่งั้น request ไม่ถึง Cloudflare (192.0.2.1 = ที่อยู่สมมติ ไม่ต้องมี origin)
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"www.$ZONE\",\"content\":\"192.0.2.1\",\"proxied\":true,\"comment\":\"lab 3c-04\"}" | jq -c '{success, errors}'
cat > redirect-rules.json <<EOF
{
"rules": [{
"description": "lab: www to apex",
"expression": "(http.host eq \"www.$ZONE\")",
"action": "redirect",
"action_parameters": {
"from_value": {
"status_code": 302,
"target_url": { "expression": "concat(\"https://$ZONE\", http.request.uri.path)" },
"preserve_query_string": true
}
}
}]
}
EOF
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_dynamic_redirect/entrypoint" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
--data @redirect-rules.json | jq -c '{success, errors}'
sleep 20
curl -sI "https://www.$ZONE/pricing?ref=lab" | grep -iE "^HTTP|^location"ผลที่ควรเห็น:
{"success":true,"errors":[]}
{"success":true,"errors":[]}
HTTP/2 302
location: https://example.com/pricing?ref=lab(ถ้ามี record www อยู่แล้ว คำสั่งแรกจะ error "already exists" — ใช้ record เดิมได้ ขอแค่เป็น proxied)
มั่นใจแล้วค่อยเปลี่ยน 302 เป็น 301 แล้วรัน PUT ซ้ำ
ทดลอง B — เพิ่ม security header ด้วย Response Header Transform
cat > header-rules.json <<EOF
{
"rules": [{
"description": "lab: security headers",
"expression": "(http.host eq \"$ZONE\")",
"action": "rewrite",
"action_parameters": {
"headers": {
"X-Content-Type-Options": { "operation": "set", "value": "nosniff" },
"Referrer-Policy": { "operation": "set", "value": "strict-origin-when-cross-origin" },
"X-Frame-Options": { "operation": "set", "value": "DENY" },
"X-Powered-By": { "operation": "remove" }
}
}
}]
}
EOF
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_response_headers_transform/entrypoint" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
--data @header-rules.json | jq -c '{success, errors}'
sleep 20
curl -sI "https://$ZONE/" | grep -iE "^x-content-type|^referrer-policy|^x-frame|^x-powered" # apex ต้องเป็น record ส้มที่มีเว็บตอบผลที่ควรเห็น:
{"success":true,"errors":[]}
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
x-frame-options: DENY(ไม่มี x-powered-by) — ตรวจคะแนนเพิ่มได้ที่ securityheaders.com
ทดลอง C — redirect หลาย path ด้วย _redirects ของ static assets (ทางเลือกฝั่งโค้ด)
ใช้โปรเจกต์ hello-edge จากระดับ 2 (assets อยู่ใน public/) ใส่ไฟล์ _redirects แล้ว deploy ใหม่
cd ~/cloud-ladder/hello-edge
cat > public/_redirects <<'EOF'
/old-blog/* /blog/:splat 301
/promo /pricing 302
EOF
npx wrangler deploy && curl -sI "https://hello-edge.[subdomain-ของคุณ].workers.dev/old-blog/hello" | grep -iE "^HTTP|^location"ผลที่ควรเห็น: HTTP/2 301 และ location: /blog/hello — ข้อดี: อยู่ใน git คู่กับโค้ด · ข้อเสีย: ใช้กับ Worker นั้นเท่านั้น · เสร็จแล้ว npx wrangler delete (ถ้าไม่ใช้ต่อ)
เก็บกวาด
for PHASE in http_request_dynamic_redirect http_response_headers_transform; do
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/$PHASE/entrypoint" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
--data '{"rules":[]}' | jq -c '{success}'
done
for ID in $(curl -s -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=100" \
| jq -r '.result[] | select(.comment=="lab 3c-04") | .id'); do
curl -s -X DELETE -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$ID" | jq -c '{success}'
done
rm -f redirect-rules.json header-rules.json(ถ้าอยากเก็บ redirect/header ไว้ใช้จริง ข้ามคำสั่ง PUT {"rules":[]} ไป)
กับดักที่เจอบ่อย
| อาการ | สาเหตุ / แก้ |
|---|---|
redirect ไม่ทำงานเลยบน www |
ไม่มี DNS record ของ www หรือเป็น DNS only → request ไม่ผ่าน Cloudflare |
| แก้ rule แล้วเบราว์เซอร์ยัง redirect แบบเก่า | เคยใช้ 301 → เบราว์เซอร์ cache ไว้ ทดสอบด้วย curl หรือหน้าต่าง private · เริ่มที่ 302 |
| redirect วนลูป | target ยังเข้าเงื่อนไขเดิม (เช่น starts_with(path, "/blog") → /blog/new) → เพิ่ม and not ... |
| form POST หายหลัง redirect | ใช้ 301/302 ซึ่ง client เปลี่ยนเป็น GET → ใช้ 307/308 |
matches ใช้ไม่ได้ |
regex ไม่มีบน Free → ใช้ wildcard / starts_with / wildcard_replace |
| ลบ rule ของเพื่อนร่วมทีมหาย | PUT entrypoint แทนที่ทั้ง phase → ใช้แดชบอร์ด หรือ Terraform (ระดับ 6c) |
สรุปจำง่าย
URL เปลี่ยนให้เห็น = Redirect · เปลี่ยนเงียบ = Rewrite · เปลี่ยน header = Transform · เปลี่ยนปลายทาง = Origin Rule · มี logic = Worker — ทดสอบด้วย 302 และ
curl -sIก่อนค่อย 301