Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varnish: cache only specific domain

I have been Googling aggressively, but without luck.

I'm using Varnish with great results, but I would like to host multiple websites on a single server (Apache), without Varnish caching all of them.

Can I specify what websites by URL to cache?

Thanks

like image 371
Rune Avatar asked Sep 16 '10 15:09

Rune


People also ask

Is Varnish Cache good?

You can use Varnish to cache both dynamic and static content: this is an efficient solution to increase not only your website speed but also your server performance. According to its developers: “It can speed up delivery with a factor of 300 – 1000x, depending on your architecture.

How do I bypass Varnish Cache?

Bypassing the cache in Varnish is done by calling return (pass) in the vcl_recv subroutine of your VCL file. This return statement will send you to the vcl_pass subroutine where a backend fetch will be triggered instead of performing a cache lookup.

How does Varnish caching work?

Varnish cache is a web application accelerator also known as caching HTTP reverse proxy. It acts more like a middle man between your client (i.e. user) and your web server. That means, instead of your web server to directly listen to requests of specific contents all the time, Varnish will assume the responsibility.

Does Varnish cache cookies?

Varnish will, in the default configuration, not cache a object coming from the backend with a Set-Cookie header present. Also, if the client sends a Cookie header, Varnish will bypass the cache and go directly to the backend.


3 Answers

(edited after comment) It's req.http.host, so in your vcl file (e.g. default.vcl) do:

sub vcl_recv {
  # dont cache foo.com or bar.com - optional www
   if (req.http.host ~ "(www\.)?(foo|bar)\.com") {
     pass;
   }
  # cache foobar.com - optional www
   if (req.http.host ~ "(www\.)?foobar\.com") {
     lookup;
   }
}

And in varnish3-vcl:

sub vcl_recv {
  # dont cache foo.com or bar.com - optional www
   if (req.http.host ~ "(www\.)?(foo|bar)\.com") {
     return(pass);
   }
  # cache foobar.com - optional www
   if (req.http.host ~ "(www\.)?foobar\.com") {
     return(lookup);
   }
}
like image 194
ivy Avatar answered Oct 29 '22 17:10

ivy


Yes,

in vcl_recv you just match the hosts that you would like not to cache and pass them. Something like this (untested):

vcl_recv {
   # dont cache foo.com or bar.com - optional www
   if (req.host ~ "(www)?(foo|bar).com") {
     return(pass);
   }
}
like image 39
perbu Avatar answered Oct 29 '22 17:10

perbu


For Varnish 4

replace lookup with hash

default.vcl:

sub vcl_recv {
  # dont cache foo.com or bar.com - optional www
   if (req.http.host ~ "(www\.)?(foo|bar)\.com") {
     return(pass);
   }
  # cache foobar.com - optional www
   if (req.http.host ~ "(www\.)?foobar\.com") {
     return(hash);
   }
}
like image 45
Abhishek Goel Avatar answered Oct 29 '22 17:10

Abhishek Goel