简体   繁体   中英

Varnish cache based on header

Currently I'm running Varnish on a server which runs about 30-40 different websites. All of these websites use the same library for handling requests (every website has it's own domain). However some of these websites are very simple and can be fully cached. What I would like to do is enable a flag in a project/website (certain header) that tells varnish to cache the request once delivered. Is such a construction possible because I don't want to edit the VCL for every project that can be fully cached and add an entry to vcl_fetch like:

if (req.http.host ~ "<website>")
{
    unset req.http.cookie;
    return (lookup)
}

Is there a proper way to do this? I did look at the Varnish flowchart but can't come up with a good solution.

Thanks in advance!

I hope that this can help you. In the example below, a custom header is used as conditional.

sub vcl_fetch {
    if (req.http.Custom-Header == "www.site.com" {
       set beresp.ttl = [...]
       [...]
     }
     elsif (req.http.Custom-Header == "www.site2.com" {
       set beresp.ttl = [...] 
      }
      else {
      [...]
      }
      return(deliver);
}

Well I just started using Varnish and liked the idea. Because well I have the trouble that I only want to cache a couple of domains and don't want to change the vcl all the time.

I looked into setting a "special" header and then let varnish do the magic.

But then I looked into the docs and there is more easy way.

header('Cache-Control: public, max-age=10');

This way varnish caches the content 10 seconds. So if you would like to cache it for ever then you would come close by using a really high integer.

// Caches the content for a year, if my calculations are right :P
header('Cache-Control: public, max-age=' . (60 * 60 * 24 * 365));

Varnish will honor the TTL expressed by the backend in the response headers. If you want site X to be cached, use mod_expires (or similar) and set TTLs correctly from the backend. If you want site Y not to be cached, set Cache-Control: s-maxage=0 and Varnish will not cache it.

If you must have a specific response header, here is some example VCL:

  sub vcl_fetch {
       if (beresp.http.x-do-not-cache) {
           set beresp.ttl = 0s;
       }
  }

Note that I'm not doing return() here. By setting the TTL and falling through to the default VCL Varnish will handle this by itself.

Varnish, by default, without changing any VCL, reads the HTTP 1.1 standard cache headers returned by the back end (Cache-Control, Expires, etc) and caches the object according to those headers. So as long as you return (lookup); in vcl_recv, Varnish is already configured to do what you want it to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM