Delivering different content to different devices

      Last updated February 12, 2020

    The easiest way to deliver different content based on the device being used is to rewrite the URL of the request based on what the user agent is. Our article on how to change the URL based on conditions describes how to do this using our user interface but in pure VCL it would look something like this:

    1
    2
    3
    4
    5
    6
    7
    8
    
    sub vcl_recv {
      if (req.http.User-Agent ~ "(?i)ip(hone|od)") {
        set req.url = "/mobile" req.url;
      } elsif (req.http.User-Agent ~ "(?i)ipad") {
        set req.url = "/tablet" req.url;
      }
    #FASTLY recv
    }
    

    The code fragment above doesn't contain a comprehensive list of mobile and tablet devices. Google has an official blog post on detecting Android mobile versus tablet and this VCL fragment from Varnish can detect several different types of devices (it doesn't, however, include Windows mobile and tablet, Blackberry Playbook, and the Kindle user agents).

    Caching multiple versions of a page

    To detect mobile and desktop devices and cache multiple versions of a page using a device detection subroutine, add the Vary header Vary: X-UA-Device to any page that has those page versions. For example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    set req.http.X-UA-Device = "desktop";
    
     if (req.http.User-Agent ~ "(?i)ip(hone|od)") {
         set req.http.X-UA-Device = "mobile";
     } elsif (req.http.User-Agent ~ "(?i)android.*(mobile|mini)") {
         set req.http.X-UA-Device = "mobile";
     } elsif (req.http.User-Agent ~ "(?i)tizen.*mobile") {
         set req.http.X-UA-Device = "mobile";
     }
    

    This instructs your origin to send proper Vary headers that tell Fastly to cache multiple versions of a page.

    Adding more categories and matching

    You can also add more categories and matching by adding new VCL snippets. For example, you can upload the following VCL snippet to put bots and crawlers in their own pool using a snippet like this:

    1
    2
    3
    
    if ( req.http.User-Agent ~ "(?i)(ads|google|bing|msn|yandex|baidu|ro|career|seznam|)bot" ) {
     set req.http.X-UA-Device = "bot";
    }
    
    Back to Top