Make LiteSpeed Cache for WordPress and QUIC.cloud save a separate mobile cache

Published:

Bit of a mouthful of a title this time, but there’s no easy way to summarise it!

I’ve been working with an older WooCommerce website this week, which serves a different template to mobile devices rather than using a responsive design.

The LiteSpeed Cache plugin for WordPress has a setting to cache separate versions, but it wasn’t working with QUIC.cloud if your hosting is running a non-LiteSpeed webserver (Apache in our case).

Talking with LiteSpeed they confirmed this is a bug which will be fixed, but it needs changes to be made to both the CDN and the plugin. As I needed it now, I wrote a quick work-around. Add the following code to the top of your wp-config.php file and you’ll get a separate mobile version cached for every page.

if (isset($_SERVER['HTTP_X_LSCACHE']) && strpos($_SERVER['HTTP_X_LSCACHE'], 'on') !== false) {
    // Inlining wp_is_mobile() since it's not loaded yet
    if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
        $is_mobile = false;
    } elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'Mobile' ) !== false // Many mobile devices (all iPhone, iPad, etc.)
               || strpos( $_SERVER['HTTP_USER_AGENT'], 'Android' ) !== false
               || strpos( $_SERVER['HTTP_USER_AGENT'], 'Silk/' ) !== false
               || strpos( $_SERVER['HTTP_USER_AGENT'], 'Kindle' ) !== false
               || strpos( $_SERVER['HTTP_USER_AGENT'], 'BlackBerry' ) !== false
               || strpos( $_SERVER['HTTP_USER_AGENT'], 'Opera Mini' ) !== false
               || strpos( $_SERVER['HTTP_USER_AGENT'], 'Opera Mobi' ) !== false ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }
    if ($is_mobile) {
        $_SERVER['HTTP_X_LSCACHE_VARY'] = 'ismobile';
        $_SERVER['LSCACHE_VARY_VALUE'] = 'ismobile';
    }
}