Jake N
Jake N

Reputation: 10583

Varnish cache for mobile

I am using Varnish cache with the following to check for a mobile/tablet device:

sub device_detection
{
    set req.http.X-Device = "pc";

    if(req.http.User-Agent ~ "iP(hone|od)" || req.http.User-Agent ~ "Android" || req.http.User-Agent ~ "Symbian" || req.http.User-Agent ~ "^BlackBerr$
    {
            set req.http.X-Device = "mobile";
    }

    if(req.http.User-Agent ~ "^PalmSource")
    {
            set req.http.X-Device = "mobile";
    }

    if(req.http.User-Agent ~ "Build/FROYO" || req.http.User-Agent ~ "XOOM" )
    {
            set req.http.X-Device = "pc";
    }

    if((req.http.Cookie ~ "(force_desktop)"))
    {
            set req.http.X-Device = "pc";
    }

    if((req.http.Cookie ~ "(force_mobile)"))
    {
            set req.http.X-Device = "mobile";
    }
}

This successfully sets a new header, I can then check this in PHP using:

if(isset($headers['X-Device']) && $headers['X-Device'] == "mobile")
{
     // do mobile stuff here 
}

My issue is that this header does not form part of the cache hash (if that is the right term). So if it is viewed on a mobile device first this is then cache for all future requests regardless of the device. And vice-a-versa if the first request comes from a desktop style device.

How can I make this header part of the hash so that I can get it from PHP reliably while still cache two versions of the site using mobile and pc?

Upvotes: 1

Views: 2485

Answers (1)

lkarsten
lkarsten

Reputation: 2981

Here is the VCL snippet you need to do this:

sub vcl_hash {
    if (req.http.X-Device) {
        hash_data(req.http.X-Device);
    }
}

This is covered in the official Varnish documentation:

https://www.varnish-cache.org/docs/3.0/tutorial/devicedetection.html

Upvotes: 3

Related Questions