Detecting Devices with Varnish's Vary Header

We recommend that you target devices using responsive web design practices, such as using CSS media queries. This is the most standards-compliant way to show a different-looking website based on the type of device that is visiting the website. This makes the browser decide what to show when the HTML arrives, rather than code that executes on our platform.

If responsive design does not meet your needs, however, you can configure Varnish to return the device name in an HTTP header based on some rules. Then you can use a Vary header to display content that Drupal generates based on the value of the device name header. This has the same advantages as responsive web design (URLs stay the same, and there is no redirection), though it can lead to increased complexity in your PHP code and difficulty in troubleshooting down the road. Be sure to document that you use this approach so that we can support you better and developers down the road know how the site is being generated for different devices.

First, read the best practices of the Vary header and how, in general, it works in Varnish. That document does not necessarily describe how Acquia has the Vary header setup, but is a good generic guide on the subject.

The implementation step is to tell Varnish to "vary" the output based on the "X-UA-Device" header. You can do this using the following one line of code, likely in a custom module:

drupal_add_http_header("Vary: X-UA-Device",  false);

What that does is say to Varnish:

  1. When device x first visits the site, Drupal will tell Varnish to cache content for device x.
  2. When the next person with device x visits the site, Varnish will serve the content that Drupal generated for device x.

Replace x for each device listed below. That is, Varnish can potentially cache different versions of content at the same URL based on what the HTTP header is set to. The possible values of this are (this is based on <a href="">the public VCL file we based our device detection on</a>, which you can inspect for how it determines what category a device fits under):

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

Contact supportStill need assistance? Contact Acquia Support