Varnish Cache Based on Device Type

41

Varnish Cache is a web application accelerator also known as a caching HTTP reverse proxy. Varnish Cache allows you to cache server request efficiently and improve server performance.

varnish Device

Serving content customized for the requesting device

Without additional configuration, Varnish will return the only version of a resource that it has cached for a particular URL — regardless of its appropriateness for the device

performing the request. This can be problematic. For example, if a mobile phone performs the first request for a resource, the request may return specific mobile content, and Varnish will likely cache it

Device detection is figuring out what kind of content to serve to a client based on the User-Agent string supplied in a request. It’s trivial and only a slight modification of default vcl configuration – to start considering user agent in cache key hash so that pages would be cached separately. Adding literal user agent value to cache key would just explode it though – there are so many variations of it’s value. To solve it we can create method, which would normalize it

sub initialize_useragent {
    if (req.http.user-agent ~ "Mobile|iPhone|Android") {
        set req.http.X-UserAgent = "mobile";
    } else {
        set req.http.X-UserAgent = "desktop";
    }
}

We could later add this normalized value in cache key hash generation as below. But this approach has one challenge that static content which doesn’t change based on device typed are hashed differently and resulting in increase in cache size and reduction cache hit rate.

# The data on which the hashing will take place
sub vcl_hash {
        hash_data(req.url);

        # Hashing based on Device(Mobile/Desktop) 
        call initialize_useragent; 
        hash_data(req.http.X-UserAgent);

        return (lookup);
}

This could easily solved by skipping Device Specific Hash addition for particular content based on requested URL parameter.

# The data on which the hashing will take place
sub vcl_hash {
        hash_data(req.url);

        # Hashing based on Device(Mobile/Desktop) but skip for static content
        call initialize_useragent; 
        if (!(req.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico") ){
            hash_data(req.http.X-UserAgent);
        }
        return (lookup);
}

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here