How do I configure Varnish so that all responses to requests matching say "*.css" gets cached in the client's browser for 30 days?

What I'm trying to achieve is making Varnish set the correct "Expires:" and/or "Cache-Control" settings so that all CSS:s are cached for 30 days regardless of what the backend says about the client-side cacheability of these objects.


This does the trick:

sub vcl_fetch {
  if (req.url ~ "\.css$") {
    set obj.http.magicmarker = "1";

sub vcl_deliver {
  if (resp.http.magicmarker) {
    unset resp.http.magicmarker;
    set resp.http.Cache-Control = "...";
    set resp.http.Expires = "...";
    set resp.http.Age = "...";
  • I had to use set beresp.http.magicmarker = "1" under Varnish 3 (Ubuntu Trusty) – Joril Apr 13 '17 at 8:51

I don't think that Varnish will let you scope the VCL rules to "*.css". You may have to ask on the Varnish mailing list for exact info on this. Scoping by MIME type should be possible.

Assuming your objects already have cache headers set but you wish to normalize them, then a modified version of this Varnish documentation VCL should help you: http://varnish.projects.linpro.no/wiki/VCLExampleLongerCaching

In general, Varnish was not built to do larger amounts of header or content rewriting. Your web servers or web application should do this better than Varnish.


I just need to point out that varnish is actually excellent for rewriting headers. Testing for any url is possible in vcl_recv, and in vcl_fetch, it is a common application for varnish. In recv, you analyze an incoming request. In fetch you analyze the backend response.

Generally, you manipulate the request in recv, and direct it to a backend, and you manipulate the response in fetch, and rewrite headers to suit, before storing the object in the cache potentially, and delivering the response.

In fetch you can do

unset beresp.http.expires;
unset beresp.http.cache-control;

as well as

set beresp.http.Cache-Control = "max-age = 2678406";

and so on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.