By Devport Team | Last updated: 2025-07-12 | 19 min read

How to Use a CDN with WordPress for Global Performance

Content Delivery Networks (CDNs) are essential for WordPress sites serving a global audience. By distributing your content across servers worldwide, CDNs reduce latency, improve load times, and enhance user experience regardless of geographic location. This comprehensive guide covers CDN selection, implementation, and optimization strategies that can reduce page load times by up to 50% for international visitors.

Whether you're running a blog with readers worldwide or an e-commerce site with global customers, implementing a CDN correctly can transform your site's performance. We'll explore different CDN providers, integration methods, and advanced techniques that maximize the benefits while avoiding common pitfalls.

Table of Contents

  1. Understanding CDN Technology
  2. Choosing the Right CDN
  3. WordPress CDN Setup
  4. Advanced CDN Configuration
  5. Performance Optimization
  6. Monitoring and Troubleshooting
  7. Cost Optimization

Understanding CDN Technology

How CDNs Work

A CDN consists of geographically distributed servers that cache and deliver content from locations closest to your users:

User Request Flow with CDN:
┌─────────┐     ┌─────────────┐     ┌──────────────┐
│  User   │────▶│ CDN Edge    │────▶│ Origin Server│
│(London) │◀────│  (London)   │◀────│  (New York)  │
└─────────┘     └─────────────┘     └──────────────┘
    ↑                   │
    │                   ▼
    │           ┌─────────────┐
    └───────────│Cached Assets│
     Fast       └─────────────┘
   Response

Benefits for WordPress Sites

// CDN Performance Impact Analysis
class CDN_Performance_Analyzer {

    public function calculate_performance_gains($site_data) {
        $metrics = [];

        // Average latency reduction
        $origin_latency = $site_data['avg_origin_latency']; // e.g., 300ms
        $cdn_latency = $site_data['avg_cdn_latency'];       // e.g., 50ms

        $metrics['latency_reduction'] = [
            'percentage' => (($origin_latency - $cdn_latency) / $origin_latency) * 100,
            'time_saved' => $origin_latency - $cdn_latency
        ];

        // Bandwidth savings
        $metrics['bandwidth_savings'] = [
            'origin_reduction' => '85-95%',
            'cost_savings' => $this->calculate_bandwidth_cost_savings($site_data)
        ];

        // Global performance improvement
        $metrics['global_performance'] = [
            'avg_improvement' => '40-60%',
            'peak_traffic_handling' => '10x capacity'
        ];

        return $metrics;
    }
}

Types of Content to Serve via CDN

Content Type CDN Suitable Cache Duration Notes
Images 1 year Immutable with versioning
CSS/JS 1 month Use fingerprinting
Fonts 1 year CORS headers required
Videos 1 year Consider specialized video CDN
HTML ✓/- 5-60 min Dynamic content challenges
API Responses ✓/- Varies Careful cache strategy needed

Choosing the Right CDN

CDN Provider Comparison

// CDN Provider Feature Matrix
$cdn_providers = [
    'Cloudflare' => [
        'free_tier' => true,
        'wordpress_plugin' => true,
        'image_optimization' => true,
        'edge_workers' => true,
        'pricing' => 'Free - $200+/month',
        'pops' => 200,
        'best_for' => 'All-purpose, budget-conscious'
    ],
    'BunnyCDN' => [
        'free_tier' => false,
        'wordpress_plugin' => true,
        'image_optimization' => true,
        'edge_workers' => true,
        'pricing' => '$0.01/GB',
        'pops' => 100,
        'best_for' => 'Cost-effective, developer-friendly'
    ],
    'KeyCDN' => [
        'free_tier' => false,
        'wordpress_plugin' => true,
        'image_optimization' => false,
        'edge_workers' => false,
        'pricing' => '$0.04/GB',
        'pops' => 40,
        'best_for' => 'Simple setup, good performance'
    ],
    'Amazon CloudFront' => [
        'free_tier' => true,
        'wordpress_plugin' => false,
        'image_optimization' => false,
        'edge_workers' => true,
        'pricing' => '$0.085/GB',
        'pops' => 400,
        'best_for' => 'AWS ecosystem, enterprise'
    ],
    'Fastly' => [
        'free_tier' => false,
        'wordpress_plugin' => false,
        'image_optimization' => true,
        'edge_workers' => true,
        'pricing' => 'Custom',
        'pops' => 60,
        'best_for' => 'Real-time purging, advanced features'
    ]
];

Selection Criteria

// CDN Selection Helper
function recommend_cdn($requirements) {
    $recommendations = [];

    // Budget constraints
    if ($requirements['budget'] < 50) {
        $recommendations[] = 'Cloudflare (Free/Pro)';
        $recommendations[] = 'BunnyCDN';
    }

    // Traffic volume
    if ($requirements['monthly_bandwidth'] > 1000) { // GB
        $recommendations[] = 'BunnyCDN';
        $recommendations[] = 'Cloudflare Enterprise';
    }

    // Geographic distribution
    if (in_array('china', $requirements['target_regions'])) {
        $recommendations[] = 'Cloudflare (China Network)';
        $recommendations[] = 'Amazon CloudFront';
    }

    // Technical requirements
    if ($requirements['needs_image_optimization']) {
        $recommendations[] = 'Cloudflare';
        $recommendations[] = 'BunnyCDN';
        $recommendations[] = 'Fastly';
    }

    return array_unique($recommendations);
}

WordPress CDN Setup

Method 1: Plugin-Based Setup (Cloudflare)

// Step 1: Install and configure Cloudflare plugin
add_action('init', function() {
    // Cloudflare plugin auto-configuration
    if (defined('CLOUDFLARE_PLUGIN_DIR')) {
        // Set optimal settings
        update_option('cloudflare_settings', [
            'automatic_cache_purge' => 1,
            'browser_cache_ttl' => 31536000, // 1 year
            'challenge_ttl' => 1800,
            'development_mode' => 0,
            'cache_level' => 'aggressive',
            'minify' => [
                'js' => 1,
                'css' => 1,
                'html' => 1
            ]
        ]);
    }
});

// Step 2: Configure page rules
$cloudflare_page_rules = [
    [
        'pattern' => '*.example.com/wp-admin/*',
        'actions' => [
            'cache_level' => 'bypass',
            'disable_apps' => true,
            'disable_performance' => true
        ]
    ],
    [
        'pattern' => '*.example.com/*.jpg',
        'actions' => [
            'cache_level' => 'cache_everything',
            'edge_cache_ttl' => 31536000,
            'browser_cache_ttl' => 31536000
        ]
    ],
    [
        'pattern' => '*.example.com/wp-content/uploads/*',
        'actions' => [
            'cache_level' => 'cache_everything',
            'edge_cache_ttl' => 2592000,
            'browser_cache_ttl' => 2592000
        ]
    ]
];

Method 2: Manual CDN Integration

// Custom CDN URL rewriting
class WordPress_CDN_Rewriter {

    private $cdn_domain;
    private $site_domain;
    private $directories;

    public function __construct($cdn_domain) {
        $this->cdn_domain = $cdn_domain;
        $this->site_domain = parse_url(home_url(), PHP_URL_HOST);
        $this->directories = ['wp-content', 'wp-includes'];

        // Hook into WordPress
        add_filter('script_loader_src', [$this, 'rewrite_url']);
        add_filter('style_loader_src', [$this, 'rewrite_url']);
        add_filter('wp_get_attachment_url', [$this, 'rewrite_url']);

        // Rewrite content URLs
        if (!is_admin()) {
            add_action('template_redirect', [$this, 'start_buffer']);
        }
    }

    public function rewrite_url($url) {
        // Skip external URLs
        if (!strpos($url, $this->site_domain)) {
            return $url;
        }

        // Check if URL contains CDN-able directory
        foreach ($this->directories as $dir) {
            if (strpos($url, $dir) !== false) {
                return str_replace($this->site_domain, $this->cdn_domain, $url);
            }
        }

        return $url;
    }

    public function start_buffer() {
        ob_start([$this, 'rewrite_buffer']);
    }

    public function rewrite_buffer($buffer) {
        // Rewrite URLs in content
        $home_url = home_url();
        $cdn_url = 'https://' . $this->cdn_domain;

        // Pattern to match WordPress content URLs
        $pattern = '#(?<=[(\"\'])' . 
                   preg_quote($home_url, '#') . 
                   '/(wp-content|wp-includes)([^\"\']+)(?=[\"\')])#';

        $replacement = $cdn_url . '/$1$2';

        return preg_replace($pattern, $replacement, $buffer);
    }
}

// Initialize CDN rewriter
new WordPress_CDN_Rewriter('cdn.example.com');

Method 3: Server-Level CDN Configuration

# Nginx configuration for CDN origin
server {
    listen 80;
    server_name origin.example.com;
    root /var/www/wordpress;

    # Set proper cache headers for CDN
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|webp|woff|woff2)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
        add_header Vary "Accept-Encoding";

        # CORS for fonts
        if ($request_filename ~* \.(woff|woff2|ttf|eot)$) {
            add_header Access-Control-Allow-Origin "*";
        }
    }

    # Dynamic content headers
    location ~ \.php$ {
        add_header Cache-Control "no-cache, must-revalidate";
        add_header X-CDN-Cache "BYPASS";

        # PHP-FPM configuration
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    # Security headers
    add_header X-Content-Type-Options "nosniff";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
}

Advanced CDN Configuration

Image Optimization via CDN

// Implement CDN-based image optimization
class CDN_Image_Optimizer {

    private $cdn_transform_url = 'https://cdn.example.com/transform';

    public function __construct() {
        add_filter('wp_get_attachment_image_src', [$this, 'optimize_image_url'], 10, 3);
        add_filter('the_content', [$this, 'optimize_content_images']);
    }

    public function optimize_image_url($image, $attachment_id, $size) {
        if (!is_array($image)) {
            return $image;
        }

        $url = $image[0];
        $width = $image[1];
        $height = $image[2];

        // Build optimization parameters
        $params = [
            'url' => $url,
            'w' => $width,
            'h' => $height,
            'q' => 85, // Quality
            'f' => 'auto', // Auto format (WebP/AVIF)
            'fit' => 'cover'
        ];

        // Generate optimized URL
        $image[0] = $this->cdn_transform_url . '?' . http_build_query($params);

        return $image;
    }

    public function optimize_content_images($content) {
        // Find all images in content
        preg_match_all('/<img[^>]+>/i', $content, $images);

        foreach ($images[0] as $image) {
            // Extract src
            preg_match('/src=["\']([^"\']+)["\']/i', $image, $src);
            if (empty($src[1])) continue;

            // Extract dimensions
            preg_match('/width=["\'](\d+)["\']/i', $image, $width);
            preg_match('/height=["\'](\d+)["\']/i', $image, $height);

            // Build optimized image tag
            $optimized_src = $this->build_optimized_url(
                $src[1], 
                $width[1] ?? null, 
                $height[1] ?? null
            );

            $new_image = str_replace($src[1], $optimized_src, $image);

            // Add loading="lazy" if not present
            if (strpos($new_image, 'loading=') === false) {
                $new_image = str_replace('<img', '<img loading="lazy"', $new_image);
            }

            $content = str_replace($image, $new_image, $content);
        }

        return $content;
    }

    private function build_optimized_url($url, $width = null, $height = null) {
        $params = ['url' => $url, 'f' => 'auto', 'q' => 85];

        if ($width) $params['w'] = $width;
        if ($height) $params['h'] = $height;

        return $this->cdn_transform_url . '?' . http_build_query($params);
    }
}

Edge Computing with CDN

// Cloudflare Worker for edge processing
addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    const url = new URL(request.url);

    // Cache key modification for better hit rates
    const cacheKey = buildCacheKey(request);

    // Check cache
    const cache = caches.default;
    let response = await cache.match(cacheKey);

    if (!response) {
        // Fetch from origin
        response = await fetch(request);

        // Modify response headers
        response = new Response(response.body, response);
        response.headers.set('Cache-Control', 'public, max-age=3600');
        response.headers.set('X-CDN-Cache', 'MISS');

        // Store in cache
        event.waitUntil(cache.put(cacheKey, response.clone()));
    } else {
        // Cache hit
        response = new Response(response.body, response);
        response.headers.set('X-CDN-Cache', 'HIT');
    }

    // Add security headers
    response.headers.set('X-Content-Type-Options', 'nosniff');
    response.headers.set('X-Frame-Options', 'SAMEORIGIN');

    return response;
}

function buildCacheKey(request) {
    const url = new URL(request.url);

    // Normalize URL for better cache hits
    url.searchParams.sort();

    // Remove marketing parameters
    const marketingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'fbclid'];
    marketingParams.forEach(param => url.searchParams.delete(param));

    return url.toString();
}

CDN Cache Purging Strategy

// Intelligent cache purging for WordPress
class Smart_CDN_Purger {

    private $cdn_api;
    private $purge_queue = [];

    public function __construct($cdn_api_credentials) {
        $this->cdn_api = new CDN_API($cdn_api_credentials);

        // Hook into WordPress events
        add_action('save_post', [$this, 'purge_post_cache'], 10, 2);
        add_action('comment_post', [$this, 'purge_comment_cache']);
        add_action('switch_theme', [$this, 'purge_all_cache']);
        add_action('shutdown', [$this, 'process_purge_queue']);
    }

    public function purge_post_cache($post_id, $post) {
        if (wp_is_post_revision($post_id)) {
            return;
        }

        // Add URLs to purge queue
        $this->purge_queue[] = get_permalink($post_id);

        // Purge category pages
        $categories = wp_get_post_categories($post_id);
        foreach ($categories as $cat_id) {
            $this->purge_queue[] = get_category_link($cat_id);
        }

        // Purge homepage and feeds
        $this->purge_queue[] = home_url('/');
        $this->purge_queue[] = get_bloginfo('rss2_url');

        // Purge related images
        if (has_post_thumbnail($post_id)) {
            $thumbnail_id = get_post_thumbnail_id($post_id);
            $this->purge_attachment_urls($thumbnail_id);
        }
    }

    public function purge_comment_cache($comment_id) {
        $comment = get_comment($comment_id);
        $this->purge_queue[] = get_permalink($comment->comment_post_ID);
    }

    public function purge_all_cache() {
        $this->cdn_api->purge_all();
    }

    public function process_purge_queue() {
        if (empty($this->purge_queue)) {
            return;
        }

        // Remove duplicates
        $this->purge_queue = array_unique($this->purge_queue);

        // Batch purge for efficiency
        $this->cdn_api->purge_urls($this->purge_queue);

        // Log purge activity
        if (WP_DEBUG_LOG) {
            error_log('CDN Purge: ' . implode(', ', $this->purge_queue));
        }
    }

    private function purge_attachment_urls($attachment_id) {
        $sizes = get_intermediate_image_sizes();

        foreach ($sizes as $size) {
            $image = wp_get_attachment_image_src($attachment_id, $size);
            if ($image) {
                $this->purge_queue[] = $image[0];
            }
        }

        // Original image
        $this->purge_queue[] = wp_get_attachment_url($attachment_id);
    }
}

Performance Optimization

CDN Performance Metrics

// Monitor CDN performance
class CDN_Performance_Monitor {

    public function collect_metrics() {
        $metrics = [
            'cache_hit_ratio' => $this->calculate_hit_ratio(),
            'bandwidth_saved' => $this->calculate_bandwidth_savings(),
            'response_times' => $this->measure_response_times(),
            'error_rates' => $this->check_error_rates()
        ];

        // Store metrics
        update_option('cdn_performance_metrics', $metrics);

        // Alert on issues
        if ($metrics['cache_hit_ratio'] < 0.7) {
            $this->send_alert('Low cache hit ratio: ' . $metrics['cache_hit_ratio']);
        }

        return $metrics;
    }

    private function calculate_hit_ratio() {
        // Get CDN analytics
        $stats = $this->cdn_api->get_analytics('24h');

        $hits = $stats['cache_hits'] ?? 0;
        $misses = $stats['cache_misses'] ?? 0;
        $total = $hits + $misses;

        return $total > 0 ? $hits / $total : 0;
    }

    private function measure_response_times() {
        $test_urls = [
            'image' => '/wp-content/uploads/test-image.jpg',
            'css' => '/wp-content/themes/theme/style.css',
            'js' => '/wp-content/themes/theme/script.js'
        ];

        $times = [];

        foreach ($test_urls as $type => $path) {
            $start = microtime(true);

            // Test CDN URL
            $cdn_url = 'https://cdn.example.com' . $path;
            wp_remote_head($cdn_url);

            $times[$type] = (microtime(true) - $start) * 1000; // ms
        }

        return $times;
    }
}

Optimizing CDN Cache Headers

// Advanced cache header management
add_action('send_headers', function() {
    if (is_admin()) {
        return;
    }

    $cache_config = [
        'post' => [
            'max_age' => 3600,
            's_maxage' => 86400,
            'stale_while_revalidate' => 86400
        ],
        'page' => [
            'max_age' => 1800,
            's_maxage' => 3600,
            'stale_while_revalidate' => 3600
        ],
        'attachment' => [
            'max_age' => 31536000,
            's_maxage' => 31536000,
            'immutable' => true
        ],
        'feed' => [
            'max_age' => 0,
            's_maxage' => 300,
            'no_cache' => true
        ]
    ];

    // Determine content type
    $type = 'page';
    if (is_single()) $type = 'post';
    if (is_attachment()) $type = 'attachment';
    if (is_feed()) $type = 'feed';

    $config = $cache_config[$type];

    // Build Cache-Control header
    $directives = [];

    if (!empty($config['no_cache'])) {
        $directives[] = 'no-cache';
    } else {
        $directives[] = 'public';
        $directives[] = 'max-age=' . $config['max_age'];
        $directives[] = 's-maxage=' . $config['s_maxage'];

        if (!empty($config['stale_while_revalidate'])) {
            $directives[] = 'stale-while-revalidate=' . $config['stale_while_revalidate'];
        }

        if (!empty($config['immutable'])) {
            $directives[] = 'immutable';
        }
    }

    header('Cache-Control: ' . implode(', ', $directives));

    // Add CDN-specific headers
    header('X-CDN-Cache-Control: ' . implode(', ', $directives));
    header('Surrogate-Control: max-age=' . $config['s_maxage']);
});

Monitoring and Troubleshooting

CDN Debugging Tools

// CDN debug information display
class CDN_Debugger {

    public function __construct() {
        if (current_user_can('manage_options') && isset($_GET['cdn_debug'])) {
            add_action('wp_footer', [$this, 'display_debug_info']);
        }
    }

    public function display_debug_info() {
        $debug_data = [
            'request_headers' => getallheaders(),
            'response_headers' => headers_list(),
            'cdn_status' => $this->check_cdn_status(),
            'cache_status' => $this->analyze_cache_headers(),
            'performance_metrics' => $this->get_performance_metrics()
        ];

        echo '<div id="cdn-debug" style="position:fixed;bottom:0;left:0;right:0;background:#000;color:#fff;padding:20px;font-family:monospace;font-size:12px;max-height:300px;overflow:auto;">';
        echo '<h3>CDN Debug Information</h3>';
        echo '<pre>' . print_r($debug_data, true) . '</pre>';
        echo '</div>';
    }

    private function check_cdn_status() {
        $test_asset = home_url('/wp-includes/css/dist/block-library/style.min.css');
        $cdn_domain = 'cdn.example.com';

        // Check if asset is served from CDN
        $response = wp_remote_head(str_replace(parse_url(home_url(), PHP_URL_HOST), $cdn_domain, $test_asset));

        return [
            'cdn_active' => !is_wp_error($response),
            'status_code' => wp_remote_retrieve_response_code($response),
            'cache_status' => wp_remote_retrieve_header($response, 'x-cache'),
            'cf_ray' => wp_remote_retrieve_header($response, 'cf-ray'),
            'server' => wp_remote_retrieve_header($response, 'server')
        ];
    }

    private function analyze_cache_headers() {
        $headers = headers_list();
        $cache_headers = [];

        foreach ($headers as $header) {
            if (stripos($header, 'cache') !== false || 
                stripos($header, 'expires') !== false ||
                stripos($header, 'pragma') !== false) {
                $cache_headers[] = $header;
            }
        }

        return $cache_headers;
    }
}

// Initialize debugger
new CDN_Debugger();

Common CDN Issues and Solutions

// CDN troubleshooting helper
class CDN_Troubleshooter {

    private $common_issues = [
        'mixed_content' => [
            'symptoms' => ['HTTPS warnings', 'Blocked resources'],
            'check' => 'check_mixed_content',
            'fix' => 'fix_mixed_content'
        ],
        'cors_errors' => [
            'symptoms' => ['Font loading errors', 'Cross-origin blocks'],
            'check' => 'check_cors_headers',
            'fix' => 'fix_cors_headers'
        ],
        'cache_misses' => [
            'symptoms' => ['Low hit ratio', 'Slow performance'],
            'check' => 'check_cache_configuration',
            'fix' => 'optimize_cache_rules'
        ],
        'purge_failures' => [
            'symptoms' => ['Stale content', 'Update delays'],
            'check' => 'check_purge_functionality',
            'fix' => 'fix_purge_configuration'
        ]
    ];

    public function diagnose_issues() {
        $issues_found = [];

        foreach ($this->common_issues as $issue => $config) {
            $check_method = $config['check'];

            if (method_exists($this, $check_method)) {
                $result = $this->$check_method();

                if ($result['has_issue']) {
                    $issues_found[$issue] = [
                        'severity' => $result['severity'],
                        'message' => $result['message'],
                        'solution' => $config['fix']
                    ];
                }
            }
        }

        return $issues_found;
    }

    private function check_mixed_content() {
        $content = file_get_contents(home_url());
        $has_http = preg_match_all('/http:\/\/[^"\s]+/i', $content, $matches);

        return [
            'has_issue' => $has_http > 0,
            'severity' => 'high',
            'message' => "Found {$has_http} HTTP resources on HTTPS page",
            'resources' => $matches[0] ?? []
        ];
    }

    private function fix_mixed_content() {
        // Force HTTPS for all resources
        add_filter('script_loader_src', [$this, 'force_https']);
        add_filter('style_loader_src', [$this, 'force_https']);
        add_filter('wp_get_attachment_url', [$this, 'force_https']);

        // Fix content URLs
        add_filter('the_content', function($content) {
            return str_replace('http://', 'https://', $content);
        });
    }

    public function force_https($url) {
        return str_replace('http://', 'https://', $url);
    }
}

Cost Optimization

Bandwidth Optimization Strategies

// CDN cost optimization
class CDN_Cost_Optimizer {

    public function analyze_usage() {
        $usage_data = $this->cdn_api->get_usage_stats('30d');

        $analysis = [
            'total_bandwidth' => $usage_data['bandwidth_gb'],
            'total_requests' => $usage_data['requests'],
            'estimated_cost' => $this->calculate_cost($usage_data),
            'optimization_opportunities' => $this->find_optimizations($usage_data)
        ];

        return $analysis;
    }

    private function find_optimizations($usage_data) {
        $optimizations = [];

        // Check for large files
        $large_files = array_filter($usage_data['top_files'], function($file) {
            return $file['size_mb'] > 5;
        });

        if (!empty($large_files)) {
            $optimizations[] = [
                'type' => 'compress_large_files',
                'potential_savings' => '20-40%',
                'files' => $large_files
            ];
        }

        // Check cache hit ratio
        if ($usage_data['cache_hit_ratio'] < 0.8) {
            $optimizations[] = [
                'type' => 'improve_cache_rules',
                'potential_savings' => '10-30%',
                'current_ratio' => $usage_data['cache_hit_ratio']
            ];
        }

        // Check for unnecessary requests
        $static_requests = $usage_data['requests_by_type']['static'];
        $dynamic_requests = $usage_data['requests_by_type']['dynamic'];

        if ($dynamic_requests > $static_requests * 0.3) {
            $optimizations[] = [
                'type' => 'reduce_dynamic_requests',
                'potential_savings' => '15-25%',
                'suggestion' => 'Implement better caching for dynamic content'
            ];
        }

        return $optimizations;
    }

    public function implement_cost_controls() {
        // Set bandwidth alerts
        $this->cdn_api->set_alert([
            'type' => 'bandwidth',
            'threshold' => 1000, // GB
            'action' => 'notify'
        ]);

        // Implement rate limiting
        add_action('init', function() {
            if ($this->is_bot_traffic()) {
                header('X-Robots-Tag: noindex');
                header('Cache-Control: no-cache, no-store');
            }
        });

        // Optimize image delivery
        add_filter('wp_get_attachment_image_attributes', function($attr, $attachment) {
            // Add lazy loading
            $attr['loading'] = 'lazy';

            // Add responsive sizing
            if (empty($attr['sizes'])) {
                $attr['sizes'] = '(max-width: 768px) 100vw, 50vw';
            }

            return $attr;
        }, 10, 2);
    }
}

CDN Configuration Best Practices

// CDN configuration recommendations
$cdn_best_practices = [
    'caching_rules' => [
        'static_assets' => [
            'pattern' => '\.(jpg|jpeg|png|gif|webp|css|js|woff|woff2)$',
            'cache_control' => 'public, max-age=31536000, immutable',
            'cdn_ttl' => '1 year'
        ],
        'html_pages' => [
            'pattern' => '\.(html|htm)$|^/$',
            'cache_control' => 'public, max-age=300, s-maxage=3600',
            'cdn_ttl' => '1 hour'
        ],
        'api_endpoints' => [
            'pattern' => '^/wp-json/',
            'cache_control' => 'no-cache, must-revalidate',
            'cdn_ttl' => 'bypass'
        ]
    ],

    'security_headers' => [
        'X-Content-Type-Options' => 'nosniff',
        'X-Frame-Options' => 'SAMEORIGIN',
        'X-XSS-Protection' => '1; mode=block',
        'Referrer-Policy' => 'strict-origin-when-cross-origin'
    ],

    'performance_settings' => [
        'enable_http2' => true,
        'enable_brotli' => true,
        'enable_early_hints' => true,
        'enable_0rtt' => true,
        'min_tls_version' => '1.2'
    ]
];

Next Steps

Now that you've mastered CDN implementation for WordPress, continue optimizing your site's performance:

  1. Implement Advanced Caching: Combine CDN with other caching layers for maximum performance
  2. Optimize Images Further: Use next-generation formats and responsive images
  3. Monitor Core Web Vitals: Ensure CDN improvements translate to better user experience
  4. Set Up Performance Monitoring: Track CDN effectiveness over time

For comprehensive performance optimization strategies, explore our complete WordPress Performance Optimization guide.


Last updated: July 12, 2025