‹‹ All posts

Split Varnish cache by user agent

14 of November, 2013


I know I know, responsive design is all over the place nowadays and discussing dedicated mobile theme is kind of forbidden and lame. Anyway this approach is still widely used and I want to show how to split Varnish cache by user agent. It is useful when back end you are using this value to decide which view to use and you want to leverage from caching as well.

In Magento, for instance, you can specify different theme according to user agent. When you put varnish in front of given installation, you have to use similar approach. 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. For instance if we care only if it’s “mobile” or “desktop” browser, if could look something like this:

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

And then we can use this normalized value in cache key hash generation:

sub vcl_hash {
    hash_data(req.url);
    call normalize_useragent;
    hash_data(req.http.X-UserAgent);
    return (hash);
}
comments powered by Disqus