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

Comments

3 comments

  • Rogier Mulhuijzen

    Yup, quite easy:

    perl 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):

    ```perl 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:

    ```perl 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); } }
    ```

  • loopj

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

  • Rogier Mulhuijzen

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

Please sign in to leave a comment.