Quick Tip: Save some caching space for static files in Varnish Cache

If you have multiple domains under the same application, and you use some files across multiple domains, you can save some caching space.

For example:

  • Assets like css or js files
  • Some images like placeholders and icons
  • Maybe even a huge folder with images for a webshop which is used across multiple domains
  • A shared folder with shared files across multiple domains

If that's the case you can remove the host = domain information so that Varnish does only save the requested file under the requested path without the host. This can look like this:

sub vcl_recv {
  if (req.url ~ "^[^?]*\.(css|map|gif|ico|jpeg|jpg|js|png|svg|txt|webm|webp|woff|woff2)(\?.*)?$" || req.url ~ "^/(storage|vendor|css|js|images)/") {
    unset req.http.host;
	unset req.http.cookie;

    return (hash);
  }
}

When Varnish looks up wether a cache entry for the current request exists, it usually checks for an entry with host + path. But if the host is not provided, it defaults to the server IP, which in this case would most probably stay the same. That way Varnish stores files only once across multiple domains, which can save you quite some cache space, depending on your application and use case.