How to configure Varnish to cache static files

This Varnish Cache configuration caches all static or semi-static (e.g. compressed scripts) files – images, javascript, css. It’s ment for single machine setup, to reduce webserver load. Webserver itself in my configuration runs on port 8080. On my server load average dropped by half in peak hours thanks to Varnish. This particular server vas doing some on-the-fly css generation, so your results may vary.

File default.vcl

#
# varnish config
# caches all static files (images, js, css, txt, flash)
# but requests from backend dinamic content
#

# webserver
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

# what files to cache
sub vcl_recv {
    if (req.url ~ "\.(png|gif|jpg|ico|txt|swf|css|js)$") {
        return(lookup);
    }
}

# strip the cookie before the image is inserted into cache
sub vcl_fetch {
    if (req.url ~ "\.(png|gif|jpg|swf|css|js)$") {
        unset beresp.http.set-cookie;
    }
}

# add response header to see if document was cached
sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *