Dressing well for less

Bandwidth efficiency with Save-Data

In this example, we're demonstrating how you adjust IO parameters based on HTTP headers.


  table io_policies {
    "article-main": "crop=660:438&width=660",
    "article-large": "crop=318:212&width=318",
    "article-medium": "crop=250:166&width=250",
    "thumb": "crop=80:53&width=80",
    "avatar": "crop=1:1&width=150",
  }


  sub vcl_recv {
  #FASTLY recv

    // Return non-image
    if (req.url.path !~ "(?i)\.(?:jpg|png)$" 
      || req.url.path !~ "/images/") {
      return(lookup);
    }

    // Signal to send to IO
    set req.http.X-Fastly-Imageopto-Api = "fastly";

    // Don't alter the request if we're running at 
    // the shield, it has already been rewritten
    if (req.http.Fastly-FF) {
        return (lookup);
    }
    
    // Support default policy functionality
    if (req.url.qs ~ "(?:^|&)policy=([^&]+)") {
      set var.pol = re.group.1;
    }
    set req.url = req.url.path "?" req.url.qs "&" 
                  table.lookup(io_policies, var.pol);

    //Handle Save-Data
    if (req.http.Save-Data) {
      set req.url = req.url.path "?" 
                    regsuball(req.url.qs, 
                              "(^|&)(dpr|quality)=[^&]+", "") 
                    "&quality=10";
    }

  }
      
  sub vcl_deliver {
  #FASTLY deliver
    
    # Vary on Save-Data
    if (!req.http.Fastly-FF) {
      if (resp.http.Vary) {
        set resp.http.Vary = resp.http.Vary ", Save-Data";
      } else {
        set resp.http.Vary = "Save-Data";
      }
    }

    return(deliver);
  }
                

  //facepug.io/images/a9/pug-dressing.jpg?policy=article-main

  //facepug.io/images/a9/pug-dressing.jpg?policy=article-main&dpr=2
                

  GET /images/a9/pug-dressing.jpg?policy=article-main&dpr=2 HTTP/1.1
  Host: facepug.io
  Connection: keep-alive
  Cache-Control: max-age=0
  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)
  Accept: image/webp,*/*,
  Save-Data: on
                
Share this story