SiamCafe.net Blog
Technology

WordPress WooCommerce Edge Deployment

wordpress woocommerce edge deployment
WordPress WooCommerce Edge Deployment | SiamCafe Blog
2025-11-10· อ. บอม — SiamCafe.net· 1,588 คำ

WordPress WooCommerce Edge Deployment คืออะไร

WordPress เป็น CMS ที่ได้รับความนิยมสูงสุดในโลก ใช้งานมากกว่า 40% ของเว็บไซต์ทั้งหมด WooCommerce เป็น e-commerce plugin สำหรับ WordPress ที่มีส่วนแบ่งตลาดมากกว่า 28% ของ online stores ทั่วโลก Edge Deployment คือการ deploy application ใกล้ผู้ใช้มากที่สุด โดยใช้ edge servers ทั่วโลก เช่น CDN edge nodes, Cloudflare Workers, AWS CloudFront Functions การ deploy WooCommerce บน edge ช่วยลด latency ให้ page load เร็วขึ้น เพิ่ม conversion rate และรองรับ traffic spikes ได้ดี

Edge Deployment Architecture

# edge_arch.py — WooCommerce edge deployment architecture
import json

class EdgeArchitecture:
    COMPONENTS = {
        "cdn_edge": {
            "name": "CDN Edge (Static Assets)",
            "role": "Cache static files (images, CSS, JS) ใกล้ผู้ใช้",
            "tools": "Cloudflare, AWS CloudFront, Fastly, Bunny CDN",
            "cache_rate": "80-95% ของ requests เป็น static — cache ได้เกือบหมด",
        },
        "edge_compute": {
            "name": "Edge Compute (Dynamic)",
            "role": "รัน logic บน edge — HTML rewriting, A/B testing, geo-routing",
            "tools": "Cloudflare Workers, AWS Lambda@Edge, Vercel Edge Functions",
            "use_case": "Personalize content, currency conversion, geo-redirect",
        },
        "origin_server": {
            "name": "Origin Server (WordPress/WooCommerce)",
            "role": "รัน PHP, MySQL, WooCommerce logic — cart, checkout, admin",
            "optimization": "Object cache (Redis), page cache, PHP OPcache, database tuning",
        },
        "database": {
            "name": "Database (MySQL/MariaDB)",
            "role": "เก็บ products, orders, users, content",
            "optimization": "Read replica, query cache, proper indexing, connection pooling",
        },
    }

    CACHING_LAYERS = {
        "browser": "Browser cache: static assets (images, CSS, JS) — Cache-Control headers",
        "cdn": "CDN edge cache: static + cacheable HTML pages — 80-95% hit rate",
        "page_cache": "Full page cache: generated HTML pages — Nginx FastCGI cache / Varnish",
        "object_cache": "Object cache: database queries, API responses — Redis / Memcached",
        "opcode_cache": "PHP OPcache: compiled PHP bytecode — built into PHP",
    }

    def show_components(self):
        print("=== Edge Architecture ===\n")
        for key, comp in self.COMPONENTS.items():
            print(f"[{comp['name']}]")
            print(f"  Role: {comp['role']}")
            print()

    def show_caching(self):
        print("=== Caching Layers ===")
        for layer, desc in self.CACHING_LAYERS.items():
            print(f"  [{layer}] {desc}")

arch = EdgeArchitecture()
arch.show_components()
arch.show_caching()

Cloudflare Edge Setup

# cloudflare.py — Cloudflare edge setup for WooCommerce
import json

class CloudflareSetup:
    PAGE_RULES = {
        "cache_static": {
            "url": "*.example.com/wp-content/*",
            "settings": "Cache Level: Cache Everything, Edge TTL: 1 month, Browser TTL: 1 year",
        },
        "bypass_cart": {
            "url": "*.example.com/cart/*",
            "settings": "Cache Level: Bypass — cart page ต้อง dynamic ทุกครั้ง",
        },
        "bypass_checkout": {
            "url": "*.example.com/checkout/*",
            "settings": "Cache Level: Bypass — checkout ต้อง dynamic + secure",
        },
        "bypass_admin": {
            "url": "*.example.com/wp-admin/*",
            "settings": "Cache Level: Bypass — admin area ต้อง dynamic",
        },
        "cache_products": {
            "url": "*.example.com/product/*",
            "settings": "Cache Level: Cache Everything, Edge TTL: 2 hours — product pages cacheable",
        },
    }

    WORKER_EXAMPLE = """
// Cloudflare Worker — Edge personalization for WooCommerce
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  const country = request.cf.country
  
  // Geo-based currency
  const currencyMap = {
    'TH': 'THB', 'US': 'USD', 'JP': 'JPY',
    'GB': 'GBP', 'DE': 'EUR', 'SG': 'SGD',
  }
  
  // Add currency header for WooCommerce
  const modifiedRequest = new Request(request, {
    headers: new Headers(request.headers)
  })
  modifiedRequest.headers.set('X-User-Currency', currencyMap[country] || 'USD')
  modifiedRequest.headers.set('X-User-Country', country)
  
  // Fetch from origin
  let response = await fetch(modifiedRequest)
  
  // Clone response to modify
  response = new Response(response.body, response)
  
  // Add security headers
  response.headers.set('X-Content-Type-Options', 'nosniff')
  response.headers.set('X-Frame-Options', 'SAMEORIGIN')
  response.headers.set('Strict-Transport-Security', 'max-age=31536000')
  
  return response
}
"""

    def show_rules(self):
        print("=== Cloudflare Page Rules ===\n")
        for key, rule in self.PAGE_RULES.items():
            print(f"[{rule['url']}]")
            print(f"  {rule['settings']}")
            print()

    def show_worker(self):
        print("=== Cloudflare Worker ===")
        print(self.WORKER_EXAMPLE[:400])

cf = CloudflareSetup()
cf.show_rules()

Python Performance Tools

# performance.py — Python performance tools for WooCommerce
import json

class WooPerformance:
    CODE = """
# woo_performance.py — Monitor and optimize WooCommerce performance
import requests
import json
import time
from datetime import datetime

class WooCommerceMonitor:
    def __init__(self, site_url):
        self.site_url = site_url.rstrip('/')
        self.results = []
    
    def measure_ttfb(self, path='/'):
        '''Measure Time To First Byte'''
        url = f"{self.site_url}{path}"
        
        start = time.time()
        resp = requests.get(url, timeout=30, allow_redirects=True)
        ttfb = time.time() - start
        
        return {
            'url': url,
            'status': resp.status_code,
            'ttfb_ms': round(ttfb * 1000),
            'size_kb': round(len(resp.content) / 1024, 1),
            'cached': 'HIT' in resp.headers.get('CF-Cache-Status', ''),
            'server': resp.headers.get('Server', 'unknown'),
        }
    
    def check_cache_headers(self, path='/'):
        '''Check caching headers'''
        url = f"{self.site_url}{path}"
        resp = requests.head(url, timeout=10)
        
        return {
            'url': url,
            'cache_control': resp.headers.get('Cache-Control'),
            'cf_cache_status': resp.headers.get('CF-Cache-Status'),
            'age': resp.headers.get('Age'),
            'etag': bool(resp.headers.get('ETag')),
            'last_modified': resp.headers.get('Last-Modified'),
            'x_cache': resp.headers.get('X-Cache'),
        }
    
    def benchmark_pages(self, pages=None):
        '''Benchmark key WooCommerce pages'''
        if pages is None:
            pages = [
                ('/', 'Homepage'),
                ('/shop/', 'Shop Page'),
                ('/product/sample-product/', 'Product Page'),
                ('/cart/', 'Cart Page'),
                ('/my-account/', 'My Account'),
            ]
        
        results = []
        for path, name in pages:
            try:
                result = self.measure_ttfb(path)
                result['page_name'] = name
                results.append(result)
            except Exception as e:
                results.append({'page_name': name, 'error': str(e)})
        
        # Summary
        ttfbs = [r['ttfb_ms'] for r in results if 'ttfb_ms' in r]
        
        return {
            'pages': results,
            'summary': {
                'avg_ttfb_ms': round(sum(ttfbs) / max(len(ttfbs), 1)),
                'min_ttfb_ms': min(ttfbs) if ttfbs else 0,
                'max_ttfb_ms': max(ttfbs) if ttfbs else 0,
                'cache_hit_rate': round(
                    sum(1 for r in results if r.get('cached')) / max(len(results), 1) * 100
                ),
            },
        }
    
    def check_woo_api_health(self, consumer_key, consumer_secret):
        '''Check WooCommerce REST API health'''
        url = f"{self.site_url}/wp-json/wc/v3/system_status"
        
        start = time.time()
        resp = requests.get(url, auth=(consumer_key, consumer_secret), timeout=10)
        elapsed = time.time() - start
        
        if resp.status_code == 200:
            data = resp.json()
            return {
                'status': 'healthy',
                'response_time_ms': round(elapsed * 1000),
                'wc_version': data.get('environment', {}).get('version'),
                'wp_version': data.get('environment', {}).get('wp_version'),
                'php_version': data.get('environment', {}).get('php_version'),
                'active_plugins': len(data.get('active_plugins', [])),
            }
        
        return {'status': 'error', 'code': resp.status_code}

# monitor = WooCommerceMonitor("https://example.com")
# benchmark = monitor.benchmark_pages()
# cache = monitor.check_cache_headers("/shop/")
"""

    def show_code(self):
        print("=== WooCommerce Monitor ===")
        print(self.CODE[:600])

perf = WooPerformance()
perf.show_code()

Optimization Checklist

# checklist.py — WooCommerce edge optimization checklist
import json

class OptimizationChecklist:
    CHECKLIST = {
        "cdn": {
            "name": "CDN Configuration",
            "items": [
                "Enable CDN (Cloudflare, CloudFront, Fastly)",
                "Cache static assets: images, CSS, JS (TTL: 1 year)",
                "Cache product pages (TTL: 2-4 hours)",
                "Bypass cache: cart, checkout, my-account, wp-admin",
                "Enable Brotli/Gzip compression",
                "Minify CSS and JS at edge",
            ],
        },
        "server": {
            "name": "Server Optimization",
            "items": [
                "PHP 8.2+ with OPcache enabled",
                "Redis/Memcached object cache",
                "Nginx FastCGI page cache (or Varnish)",
                "HTTP/2 or HTTP/3 enabled",
                "Database: MariaDB 10.11+ with query cache",
            ],
        },
        "woocommerce": {
            "name": "WooCommerce Optimization",
            "items": [
                "Limit products per page (12-24)",
                "Disable unused WooCommerce features",
                "Use transients for API caching",
                "Optimize product images (WebP, lazy loading)",
                "Minimize active plugins (< 20)",
            ],
        },
        "monitoring": {
            "name": "Monitoring",
            "items": [
                "TTFB monitoring (target: < 200ms cached, < 800ms uncached)",
                "Cache hit rate monitoring (target: > 85%)",
                "Core Web Vitals: LCP, FID, CLS",
                "Uptime monitoring (Uptime Kuma, Pingdom)",
            ],
        },
    }

    def show_checklist(self):
        print("=== Optimization Checklist ===\n")
        for key, section in self.CHECKLIST.items():
            print(f"[{section['name']}]")
            for item in section['items'][:4]:
                print(f"  ☐ {item}")
            print()

checklist = OptimizationChecklist()
checklist.show_checklist()

Docker Edge Setup

# docker.py — Docker setup for WooCommerce
import json

class DockerSetup:
    COMPOSE = """
# docker-compose.yaml — WooCommerce with Redis + Nginx cache
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./nginx/cache:/var/cache/nginx
      - wordpress:/var/www/html
    depends_on:
      - wordpress

  wordpress:
    image: wordpress:php8.2-fpm
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: wp
      WORDPRESS_DB_PASSWORD: 
      WORDPRESS_DB_NAME: wordpress
    volumes:
      - wordpress:/var/www/html
      - ./php/uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
    depends_on:
      - db
      - redis

  db:
    image: mariadb:10.11
    environment:
      MYSQL_ROOT_PASSWORD: 
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wp
      MYSQL_PASSWORD: 
    volumes:
      - db_data:/var/lib/mysql

  redis:
    image: redis:7-alpine
    command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru

volumes:
  wordpress:
  db_data:
"""

    def show_compose(self):
        print("=== Docker Compose ===")
        print(self.COMPOSE[:500])

docker = DockerSetup()
docker.show_compose()

FAQ - คำถามที่พบบ่อย

Q: WooCommerce ช้า ต้องทำอย่างไร?

A: 3 อันดับแรก: 1) ใช้ CDN (Cloudflare free tier ก็ดี) — ลด TTFB 50-80% 2) เปิด Redis object cache — ลด database queries 60-80% 3) ใช้ page cache (Nginx FastCGI หรือ WP Super Cache) — cache HTML ทั้งหน้า เพิ่มเติม: PHP 8.2+, image optimization (WebP), ลด plugins ที่ไม่จำเป็น เป้าหมาย: TTFB < 200ms (cached), < 800ms (uncached)

Q: Cloudflare Free plan พอสำหรับ WooCommerce ไหม?

A: พอสำหรับร้านเล็ก-กลาง: CDN, DDoS protection, SSL, basic page rules Free plan ข้อจำกัด: 3 page rules, ไม่มี Workers (ต้อง Pro), ไม่มี WAF rules Pro ($20/month) แนะนำ: เพิ่ม WAF, more page rules, Polish (image optimization), Rocket Loader Business ($200/month): สำหรับร้านใหญ่ — custom rules, 100% SLA

Q: Edge deployment กับ headless WooCommerce อันไหนดีกว่า?

A: Edge deployment (traditional WooCommerce + CDN): ง่ายกว่า, ใช้ plugins ได้หมด, ไม่ต้อง develop frontend ใหม่ Headless (WooCommerce API + Next.js/Nuxt): เร็วกว่า, flexible UI, SEO ดี, แต่ develop ยากกว่ามาก เลือก Edge: ร้านเล็ก-กลาง, ไม่มี dev team, ต้องการ plugins เลือก Headless: ร้านใหญ่, มี dev team, custom UI, performance สำคัญมาก

Q: Redis กับ Memcached อันไหนดีกว่าสำหรับ WooCommerce?

A: Redis แนะนำ: persistent storage, data structures (lists, sets), pub/sub, Lua scripting Memcached: simple key-value, slightly faster for simple cache, multi-threaded สำหรับ WooCommerce: Redis ดีกว่า — session storage, transients, object cache ในตัวเดียว WordPress plugins: Redis Object Cache (free), WP Redis — ใช้ง่าย

📖 บทความที่เกี่ยวข้อง

WordPress WooCommerce Cloud Migration Strategyอ่านบทความ → WordPress WooCommerce Load Testing Strategyอ่านบทความ → PostgreSQL JSONB Edge Deploymentอ่านบทความ → WordPress WooCommerce สำหรับมือใหม่ Step by Stepอ่านบทความ → WordPress WooCommerce CQRS Event Sourcingอ่านบทความ →

📚 ดูบทความทั้งหมด →