How do I restrict caching to a specific directory using VCL?


#1

I’m looking to cache only our /assets/ path, and redirect all paths to the origin domain, is this possible with VCL?


#2

Yup, quite easy:

sub vcl_recv {
  if (!req.url ~ "^/assets/") {
    return(pass);
  } else {
    return(lookup);
  }
}

Or if you don’t want to pass through but redirect with 301 or 302 status (note that this would be horrible for POSTs):

sub vcl_recv {
  if (!req.url ~ "^/assets/") {
    error 850 "redirect";
  } else {
    return(lookup);
  }
}

sub vcl_error {
  if (obj.status == 850) {
    set obj.http.Location = "http://origin.example.com" req.url;
    set obj.status = 301; # or 302 if this redirect shouldn't be cached by the browser
    return(deliver);
  }
}   

The problem with POST requests is that you can’t 301/302 redirect them, and thus it will break those requests horribly. To avoid this, you could combine the two examples like so:

sub vcl_recv {
  if (!req.url ~ "^/assets/") {
    if (req.method != "GET" && req.method != "HEAD") {
      return (pass);
    } else {
      error 850 "redirect";
    }
  } else {
    return(lookup);
  }
}

sub vcl_error {
  if (obj.status == 850) {
    set obj.http.Location = "http://origin.example.com" req.url;
    set obj.status = 301; # or 302 if this redirect shouldn't be cached by the browser
    return(deliver);
  }
}   

#3

Thanks! Now if I could only work out how to add this snippet to our fastly dashboard :slight_smile:


#4

Well, which of the snippets do you want to implement? (Please don’t say the hybrid one. :wink: )