WordPress mobile version is not responsive anymore after installing varnish

It’ entirely possible that WordPress detects the device based on the User-Agent requests header and displays the right version of the website accordingly.

If you don’t instruct Varnish to create a cache variation depending on the device, only one version will be cached per page.

Device detection

Varnish is able to perform device detection by performing User-Agent introspection. You could include the following VCL snippet to accelerate the process: https://github.com/varnishcache/varnish-cache/blob/master/etc/devicedetect.vcl.

In order to trigger the device detection subroutine, the devicedetect.vcl file needs to be included and executed via call devicedetect as illustrated below:

include "devicedetect.vcl";
sub vcl_recv {
    call devicedetect;
}

The VCL code will generate a custom X-UA-Device request header that contains the device type. This will be either:

  • pc
  • bot
  • mobile-bot
  • mobile-iphone
  • mobile-firefoxos
  • mobile-smartphone
  • mobile-generic
  • mobile-smartphone
  • mobile-android
  • tablet-ipad
  • tablet-android
  • tablet-rim
  • tablet-hp
  • tablet-microsoft
  • tablet-kindle

Cache variation

Based on the X-UA-Device header, you can create a cache variation by modifying the sub vcl_hash logic:

sub vcl_hash {
  if(req.http.X-UA-Device ~ "(mobile|tablet)") {
    hash_data("mobile");
  }
}

This VCL snippet makes sure there is a 2nd version of the cached object for mobile devices and tablets.