พา WordPress ขึ้น edge ด้วย Cloudflare โดยไม่ต้องเขียนปลั๊กอิน
ตั้ง cache rule, Worker และ early hints ให้ WordPress เสิร์ฟจาก edge 90% ของ request — พร้อมกับดักที่ทำให้แคชพังเงียบ ๆ
- เผยแพร่
- 10 มิถุนายน 2568
- อ่าน
- 2 นาที
- เขียนโดย
- SSUSEMAN

เว็บ WordPress ส่วนใหญ่มีทราฟฟิกที่ 80–95% เป็นหน้าเดิม ๆ ที่ไม่เปลี่ยนตามผู้ใช้ แต่เรากลับให้ PHP render ใหม่ทุกครั้ง Cloudflare แก้ปัญหานี้ได้โดยไม่ต้องแตะโค้ดธีม
ก่อนอื่น: รู้จักทราฟฟิกของตัวเอง
เปิด Analytics ดูว่า path ไหนกิน request มากที่สุด ในเคสจริงของผม 5 path แรกคิดเป็น 78% ของ request ทั้งหมด — ทั้งหมดเป็นหน้า article ที่ไม่เปลี่ยน
Cache Rule ที่ปลอดภัย
แคชเฉพาะ GET ที่ไม่มีคุกกี้ล็อกอิน และไม่ใช่ path ของแอดมิน:
(http.request.method eq "GET"
and not http.request.uri.path contains "/wp-admin"
and not http.request.uri.path contains "/wp-login"
and not http.request.uri.path contains "/cart"
and not http.cookie contains "wordpress_logged_in"
and not http.cookie contains "woocommerce_cart_hash")
-> Cache eligible, Edge TTL 1 hour, Browser TTL 10 minutes
Worker เล็ก ๆ ที่ช่วยได้มาก
ใช้ Worker ทำสามอย่าง: ตัด query string ที่ไม่จำเป็น, เพิ่ม Early Hints และเสิร์ฟหน้า fallback เมื่อ origin ล่ม
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
['fbclid', 'gclid', 'utm_source', 'utm_medium'].forEach((k) => url.searchParams.delete(k));
const cacheKey = new Request(url.toString(), request);
const cache = caches.default;
let res = await cache.match(cacheKey);
if (res) return res;
res = await fetch(cacheKey, { cf: { cacheEverything: false } });
if (res.ok) {
const headers = new Headers(res.headers);
headers.set('Cache-Control', 'public, max-age=600, s-maxage=3600');
ctx.waitUntil(cache.put(cacheKey, new Response(res.body, { ...res, headers })));
}
return res;
},
};
Early Hints จาก origin
ถ้า origin ส่ง Link header มาพร้อม 103 Early Hints เบราว์เซอร์จะเริ่มโหลด CSS และฟอนต์ก่อนที่ HTML จะมาถึง ช่วย LCP ได้ 100–300ms ในงานจริง
Header add Link "</wp-content/themes/suseman/style.css>; rel=preload; as=style"
Header add Link "</fonts/inter-var.woff2>; rel=preload; as=font; crossorigin"
กับดักที่ทำให้แคชพัง
- คุกกี้จากปลั๊กอิน analytics ทำให้ทุก request ไม่ผ่านแคช ตั้ง bypass rule ให้ตรงจุด
- nonce ใน HTML ถ้าแคชหน้า checkout จะได้ nonce เก่าและฟอร์มส่งไม่ได้
- geo-based currency ต้องใช้ Vary หรือ cache key แยกตาม country
- purge ตอน publish ลืม purge tag archive ทำให้หน้าเก่าค้างเป็นชั่วโมง
ทดสอบเสมอ: ใช้
curl -Iดูcf-cache-statusทั้งตอนล็อกอินและไม่ล็อกอิน ถ้าได้ HIT ผิดหน้า แปลว่า rule หลวมเกินไป
ผลลัพธ์
หลังปรับ stack นี้ให้เว็บข่าวไทยแห่งหนึ่ง: cache hit rate 91%, TTFB เฉลี่ย 140ms, ภาระที่ origin ลดลง 87% และค่าเซิร์ฟเวอร์ลดลงครึ่งหนึ่ง
เขียนโดย
SUSEMAN · วิศวกรโครงสร้างพื้นฐาน · นักเขียน
บันทึกวิศวกรรมคลาวด์และเว็บ · กรุงเทพฯ ประเทศไทย
จดหมายรายสัปดาห์
สรุปบทความใหม่ เครื่องมือที่ลองแล้ว และบทเรียนจากการ deploy — ส่งทุกวันพฤหัส ไม่มีสแปม


