Integrating KeyCDN with Kinsta caching

It’s recommend that you use a CDN with Kinsta. This is due to the fact that they charge overage fees on data transferred. Currently Kinsta doesn’t have a built-in CDN option however they have stated that they are working on a solution. Until then I recommend using KeyCDN with Kinsta.

Setting up KeyCDN with Kinsta is pretty simple. I’d recommend checking out their instructions. Once both KeyCDN zones are setup and you have CDN Enabler configured all links to assets will be served from KeyCDN instead of your WordPress site.

Clearing Kinsta’s cache should clear your CDN cache

After running Kinsta with KeyCDN for few months, I discovered a common issue with development. It’s common for developers to manually purge server cache after deploying new theme updates. However since theme css and js files are now served from KeyCDN it also requires an extra step of clearing KeyCDN’s cache. Clearing both Kinsta cache and KeyCDN cache got to be pretty cumbersome so I wrote some code to make Kinsta cache purge KeyCDN.

Store sensitive information inside wp-config.php

Whenever doing custom code it’s best to keep sensitive information somewhere safe like your wp-config.php file. In order to setup an API call to KeyCDN you’ll need their API along with the zone your targeting. I defined those in my wp-config.php file like so.

define( 'KEYCDN_API_KEY', 'XXXXXXXXXXXXXXXXXXXXXX' );
define( 'KEYCDN_ZONE_ID', 'XXXXX' );

Hooking into something when there are no hooks

Screen Shot 2017-06-07 at 11.02.56 AM.png

The Kinsta caching plugin is a must use plugin. After reviewing the code I didn’t use any action hooks which I could use. They do have a few filter hooks for adding custom urls to purge however not useful for what I was wanted to do. So instead I created the following code to run after a purge happens based on landing url Kinsta goes to when the purge has completed like so /?kinsta-cache-cleared=true. The following code will detect when someone presses the Kinsta clear cache and then purge the KeyCDN zone.

// Purge CDN cache when Kinsta cache is cleared
function clear_cache_keycdn() {
    if( !empty( $_GET['kinsta-cache-cleared'] ) && $_GET['kinsta-cache-cleared'] == 'true' ) {
        
        $url = "https://api.keycdn.com/zones/purge/".KEYCDN_ZONE_ID.".json"; 
        $username = KEYCDN_API_KEY;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, "$username:");
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
    }
}

add_action( 'init', 'clear_cache_keycdn' );