Skip to content

KeyCDN with WordPress: publish-time purge, geo-targeting, image optimization

KeyCDN handles the basics well; making it survive editorial workflows means wiring publish-time purge, geo-targeting, and the image optimization service correctly.

You move a publication’s static assets and uploads to KeyCDN. Page load drops 600 ms. Two weeks later a content editor swaps a hero image on a high-traffic post — same filename — and the old image keeps serving from edge for 16 hours. Then somebody asks why visitors in Asia get a different cache freshness than EU visitors. Then the SEO lead notes that KeyCDN’s image optimization service is rewriting <img> URLs but ignoring the <picture> srcset. KeyCDN is straightforward at the pull-zone level; the parts that bite are publish-time purge, geo-targeting nuances, and the image processing rewrite layer.

What’s happening

KeyCDN serves your zone from 30+ PoPs and supports two zone types relevant to WordPress:

  • Pull Zone — origin-pull, cache-by-URL, TTL-driven invalidation. This is the standard configuration for both assets and HTML.
  • Push Zone — operator uploads directly via FTP/SFTP. Rarely useful for WordPress unless you have a CI pipeline pushing built assets.

For WordPress on a pull zone, the friction points are:

  • Purge granularity. KeyCDN’s API supports single-URL purge, tag-based purge (cache-tags applied to responses via Cache-Tag header), and full-zone purge. Single-URL is what the WP plugins ship with; tag-based is what makes “purge everything in the news category” a one-call operation instead of a loop.
  • Geo-targeting via geoip headers vs origin logic. KeyCDN injects X-Geo-Country etc. on requests to origin if you enable Geo-IP headers on the pull zone. WordPress plugins that vary content by country (cookie consent banners, currency switchers) need this header — without it, edge caches one version per URL globally, defeating the targeting.
  • Image processing service (formerly Optimus). KeyCDN can rewrite URLs to add ?width=, ?height=, ?format=webp parameters that resize and re-encode images at the edge. The WP integration plugin only rewrites wp_get_attachment_image output; manual <img> tags in post HTML, srcset entries, and image fields in builders are not touched unless you configure URL rewrites at the theme or filter layer.

How to verify

Confirm the pull zone is serving and the cache header is set:

curl -sI https://cdn.example.com/wp-content/uploads/2026/05/hero.jpg \
  | grep -iE '^(x-cache|x-edge-location|cache-tag|cache-control|age)'

Healthy hit:

x-cache: HIT
x-edge-location: FRA
cache-control: public, max-age=31536000
age: 4823

Check Geo-IP headers are reaching origin:

# On origin
tail -200 /var/log/nginx/access.log | head -3
# Use the access log format below — look for the geo fields

Configure the origin nginx access log to include the geo fields so you can audit them:

log_format keycdn '$remote_addr - $remote_user [$time_local] '
                  '"$request" $status $body_bytes_sent '
                  '"$http_referer" "$http_user_agent" '
                  'geo=$http_x_geo_country/$http_x_geo_city '
                  'real=$http_x_forwarded_for';

access_log /var/log/nginx/access.log keycdn;

Check the image optimization URLs being generated. Open a post in the front-end, view source, and look for <img src="https://cdn.example.com/.../image.jpg?width=800&height=600">. If you see <img> tags pointing at the bare origin (e.g., https://www.example.com/wp-content/uploads/...), the URL rewriter isn’t catching them.

Check purge round-trip latency:

KEYCDN_API_KEY="<your-key>"
ZONE_ID=12345
time curl -sX DELETE -u "$KEYCDN_API_KEY:" \
  https://api.keycdn.com/zones/purgeurl/$ZONE_ID.json \
  -H "Content-Type: application/json" \
  -d '{"urls":["www.example.com/sample-post/"]}'

A healthy purge returns in under 1.5 seconds and the URL is invalidated at all PoPs within ~30 seconds.

The fix

Step 1 — create the pull zone with the right settings:

KEYCDN_API_KEY="<your-key>"

curl -u "$KEYCDN_API_KEY:" -X POST https://api.keycdn.com/zones.json \
  -d '{
    "name": "example",
    "type": "pull",
    "originurl": "https://origin.example.com",
    "force_ssl": "enabled",
    "expire": 0,
    "cors": "enabled",
    "gzip": "enabled",
    "imgproc": "enabled",
    "geoiprules": "enabled",
    "cachexpiremode": 0
  }'

Key flags:

  • imgproc: enabled — turns on the image processing service.
  • geoiprules: enabled — injects X-Geo-Country, X-Geo-Region, X-Geo-City on requests to origin.
  • cachexpiremode: 0 — respect origin Cache-Control headers (recommended for WP where origin sets policy).

Step 2 — bind your zone alias and TLS:

curl -u "$KEYCDN_API_KEY:" -X POST https://api.keycdn.com/zonealiases.json \
  -d '{"name": "cdn.example.com", "zone_id": 12345}'

# Let KeyCDN provision the TLS certificate
curl -u "$KEYCDN_API_KEY:" -X PUT https://api.keycdn.com/zones/12345.json \
  -d '{"sslcert": "letsencrypt"}'

DNS:

cdn.example.com.    300    CNAME    example-12345.kxcdn.com.

Step 3 — configure origin to emit Cache-Tag so you can do bulk purges:

# /etc/nginx/conf.d/wordpress-keycdn.conf
location ~* \.(jpg|jpeg|png|gif|webp|avif|svg|css|js|woff|woff2)$ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    add_header Cache-Tag "asset" always;
}

location / {
    try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    # WordPress will emit Cache-Tag via mu-plugin (see step 4)
}

Step 4 — emit per-page Cache-Tag headers from WordPress so KeyCDN can purge by tag:

<?php
// wp-content/mu-plugins/sh-keycdn-cache-tags.php
add_action('send_headers', function() {
    if (is_admin() || is_user_logged_in()) return;
    $tags = ['wp'];
    if (is_singular()) {
        $tags[] = 'post-' . get_the_ID();
        $tags[] = 'type-' . get_post_type();
        foreach (get_the_category() as $cat) $tags[] = 'cat-' . $cat->term_id;
        foreach (get_the_tags() ?: [] as $t)  $tags[] = 'tag-' . $t->term_id;
    } elseif (is_category() || is_tag() || is_tax()) {
        $tags[] = 'archive-' . get_queried_object_id();
    } elseif (is_home() || is_front_page()) {
        $tags[] = 'home';
    }
    header('Cache-Tag: ' . implode(',', array_unique($tags)));
});

Step 5 — wire publish-time purge by tag. Saving a post in category 5 should invalidate all pages tagged cat-5:

<?php
// wp-content/mu-plugins/sh-keycdn-purge.php
define('SH_KEYCDN_API_KEY', 'your-key');
define('SH_KEYCDN_ZONE_ID', 12345);

function sh_keycdn_purge_tags(array $tags): void {
    $body = json_encode(['tags' => array_values(array_unique($tags))]);
    wp_remote_request(
        'https://api.keycdn.com/zones/purgetag/' . SH_KEYCDN_ZONE_ID . '.json',
        [
            'method'  => 'DELETE',
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(SH_KEYCDN_API_KEY . ':'),
                'Content-Type'  => 'application/json',
            ],
            'body'    => $body,
            'timeout' => 5,
        ]
    );
}

add_action('save_post', function($post_id, $post) {
    if (wp_is_post_revision($post_id) || $post->post_status !== 'publish') return;
    $tags = ['post-' . $post_id, 'home'];
    foreach (get_the_category($post_id) as $cat) $tags[] = 'cat-' . $cat->term_id;
    foreach (get_the_tags($post_id) ?: [] as $t)  $tags[] = 'tag-' . $t->term_id;
    sh_keycdn_purge_tags($tags);
}, 10, 2);

Step 6 — make the image optimization service actually rewrite the URLs that matter. Out of the box it only intercepts WordPress media helper functions. Cover manual HTML in post content with a filter:

<?php
// wp-content/mu-plugins/sh-keycdn-image-rewrite.php
define('SH_KEYCDN_HOST', 'cdn.example.com');
define('SH_ORIGIN_HOST', 'www.example.com');

add_filter('the_content', function($html) {
    return preg_replace_callback(
        '#<img([^>]+)src=["\']https?://' . preg_quote(SH_ORIGIN_HOST, '#') . '(/wp-content/uploads/[^"\']+)["\']#i',
        function($m) {
            return '<img' . $m[1] . 'src="https://' . SH_KEYCDN_HOST . $m[2] . '"';
        },
        $html
    );
}, 99);

// Also rewrite srcset
add_filter('wp_calculate_image_srcset', function($sources) {
    foreach ($sources as &$src) {
        $src['url'] = str_replace(
            'https://' . SH_ORIGIN_HOST . '/wp-content/uploads/',
            'https://' . SH_KEYCDN_HOST . '/wp-content/uploads/',
            $src['url']
        );
    }
    return $sources;
});

Step 7 — add WP-CLI helpers for operators:

# Full zone purge after a theme update
wp eval '
wp_remote_request(
  "https://api.keycdn.com/zones/purge/12345.json",
  ["method"=>"GET","headers"=>["Authorization"=>"Basic ".base64_encode("YOUR_KEY:")]]
);'

# Purge a category tag
wp eval '
wp_remote_request(
  "https://api.keycdn.com/zones/purgetag/12345.json",
  ["method"=>"DELETE","headers"=>["Authorization"=>"Basic ".base64_encode("YOUR_KEY:"),"Content-Type"=>"application/json"],
   "body"=>json_encode(["tags"=>["cat-5"]])]
);'

Step 8 — verify the geo-targeting plumbing. If your theme varies content by X-Geo-Country, the edge needs to vary the cache key on it too. In the KeyCDN dashboard under Edge Rules:

URL pattern: /
Condition: matches "*"
Action: Cache by header → X-Geo-Country

Or via API:

curl -u "$KEYCDN_API_KEY:" -X PATCH https://api.keycdn.com/zones/12345.json \
  -d '{"cachekeyheader": "X-Geo-Country"}'

After 24 hours, KeyCDN’s analytics → cache hit ratio per zone should sit above 95% for asset traffic and above 88% for HTML. If HTML is lower, see the cookie audit pattern from the BunnyCDN article — it’s almost always the same root cause.


Stack Harbor configures KeyCDN for WordPress sites under enterprise WordPress support operations, including the mu-plugin layer and the geo-vary tuning above. If your CDN dashboard says “good” but the back-button still feels slow, book a performance review.