How to Set Varnish Cache-Control Headers

Kevin Gleeson picture Kevin Gleeson · Jan 25, 2012 · Viewed 37.6k times · Source

I am hoping someone can advise on the proper method for getting Varnish to send cache-control headers. Currently, my configuration is sending "Cache-Control: no-cache" to clients.

Thanks in advance to anyone who might be able to help...

Answer

ivy picture ivy · Jan 26, 2012

Your back-end is sending "Cache-Control: no-cache" to Varnish which implies two things:

  • Varnish will not store the response in the cache (so a next lookup will fail)
  • Your clients (browsers and intermediate proxies) will not cache responses (and request them over and over).

The solution is simple: remove the cache-control headers after fetching the response from the back-end (and before storing them in the cache).

In your vcl file do:

sub vcl_fetch {
  remove beresp.http.Cache-Control;
  set beresp.http.Cache-Control = "public";
}

You can choose to only do this for certain urls (wrap it in ( if req.url ~ "" ) logic) and do way more advanced stuff.