[Varnish] Separate cache for mobile device

Let’s say you have a website with two version, one intended for ‘desktop’ browser the other for ‘mobile’ device. Both use the same domain name. How can you get two separate caches ?

The wrong answer

Add the value of the User-Agent field into your vcl_hash function. That simple enough, right ? Wrong ! Very wrong. The User-Agent field is a total mess and it has so many possible values that this setting will make Varnish completely useless. Never do that !

The good answer

To ensure two separate cache you must add into the vcl_hash an header with only two possible value: one for all the ‘desktop’ User-Agent, the other for all the ‘mobile’ ones. That means add a custom header which value will depend on a whole bunch of regex, parsing and sanitizing the horrendous User-Agent value.

Fortunately for you, this annoying task has already been done. You can find a VCL for this specific task here. Import it into your main varnish configuration file and then adjust your vcl_hash for non-static content like this:

sub vcl_hash {
  if (req.url !~ "(?i)\.png|gif|jpeg|jpg|ico|gz|tgz|bz2|tbz|mp3|ogg|zip|rar|otf|ttf|eot|woff|svg|pdf)$") {
     hash_data(req.http.X-UA-Device);
  }
}