Nginx – Varnish and nginx (Multiple site VCL configuration)

nginxvarnish

I have one VPS serving 2 WordPress installations. Using Varnish > Nginx > PHP-FPM
Right now I have this in the conf.d folder of nginx:

domain1.com.conf
domain2.com.conf

A configuration example for one domain goes like this:

server {
    server_name domain1.com www.domain1.com *.domain1.com;
    listen 127.0.0.1:81;
    expires max;
    root /home/domain1.com;

    index index.php;

The default VCL file for Varnish:

backend default {
  .host = "127.0.0.1";
  .port = "81";
  .connect_timeout = 600s;
    .first_byte_timeout = 600s;
    .between_bytes_timeout = 600s;
}

All the domains have the same listen value, 127.0.0.1:81.

How do I make Varnish to actually serve the cached version of the right domain?

Best Answer

To split your cache by domain name change your VCL configuration with next: add this to vcl_hash subroutine:

for varnish 2.1.x

if (req.http.host) {
 set req.hash += req.http.host;
}
else {
 set req.hash += server.ip;
}

for varnish 3.x

if (req.http.host) {
 hash_data(req.http.host);
}
else {
 hash_data(server.ip);
}