Search code examples
varnishvarnish-vclvarnish-4varnish-3

Varnish how to cache for mobile and desktop site


I want to know how to cache for mobile and desktop site. I have mobile and desktop site whose root is written in nginx. Mobile/Desktop is served to the user based on the user-agent whenever the user visits the site, so in this scenario how to cache for mobile and cache for desktop site so that when the user visits the website, Get the right content from the cache.

Please help to write VCL for mobile and desktop cache in Varnish.


Solution

  • You can download https://github.com/varnishcache/varnish-devicedetect/blob/master/devicedetect.vcl and include this file in your main VCL file. By calling the devicedetect subroutine in your main VCL file.

    This subroutine will set a X-UA-Device header that contains the device type, which you can then vary on.

    Here's an example:

    vcl 4.1;
    
    backend default {
        .port = "8080";
    }
    
    include "devicedetect.vcl";
    
    sub vcl_recv {
        call devicedetect;
        if(req.http.X-UA-Device ~ "^(mobile|tablet)\-.+$") {
            set req.http.X-UA-Device = "mobile";
        } else {
            set req.http.X-UA-Device = "desktop";
        }
    }
    
    sub vcl_hash {
        hash_data(req.http.X-UA-Device);
    }