Cache a specific URL with Varnish

I wanted to cache one specific route in my application with Varnish, and let everything else through. It took a bit of trial and error, but I finally found a solution that works:

Edit /etc/varnish/default.vcl and set vcl_recv to be:

sub vcl_recv {
    if (! req.url ~ "^/path/to/cache/") {
        return(pass);
    }
    return(lookup);
}

The path to cache uses the tilde operator, which allows you to supply regular expressions.

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Thanks for this tip. I assume that by removing the exclamation mark from the IF statement it would cache all routes apart from this one?

michael 2013-11-13

That’s what I’d expect 🙂

MaXe 2014-02-06

An expression such as:
if (req.url ~ “^/crontab\.php$”) {
return (pass);
}

Will cache everything else except crontab.php

Comments are closed.

Leave a comment?