Reporting whether Varnish delivered file from cache or not

When calling a resource from Varnish, it can be difficult to tell whether the resource was retrieved from Varnish’s cache, or whether it had to go to the source server to fetch it. In most cases we want the resource to come straight from Varnish’s cache – that’s the whole point of using it – so it’s nice to know when that happens.

Edit the config file with the following:

sub vcl_deliver {
        if (obj.hits > 0) {
                set resp.http.X-Cache = "HIT";
        } else {
                set resp.http.X-Cache = "MISS";
        }
}

This code adds a new header of either HIT or MISS. The header can be viewed using Chrome developer tools within the Network tab, or via a similar tab in Firebug.

Setup a simple reverse proxy using Varnish

How to setup Varnish as a simple reverse proxy.

The first step is to define the source domain. This is where all your files are stored. Edit the config file with the following:

backend mydomain {
  .host = "www.mydomain.com";
  .port = "80";
}

Now we have defined the source of the data, we want to tell Varnish when to call this. For the following code to work, the domain static.mydomain.com must be setup to point to the Varnish server.

sub vcl_recv {
   if (req.http.host ~ "static.mydomain.com") {
    set req.http.host = "www.mydomain.com";
    set req.backend = mydomain;
   }
}

That’s how to setup a single domain. You can of course handle multiple domains by defining multiple backends, and altering the logic within vcl_recv.

Removing all cookies from a request

By default, Varnish won’t cache a page that contains cookies. It’s thinking is that a cookie suggests that the page is unique to that user, and it could cause issues if it was cached. If you cached a page unique to user X, all other users would see their content.

If we feel that we do not need the cookie (it might be used for analytics and can safely be removed) It’s possible to remove the cookie from the request, allowing Varnish to cache the content. To do this, edit the VCL file with the following:

unset req.http.cookie;

This must be placed inside sub vcl_recv. The following is a very basic example that would remove all cookies from all requests

sub vcl_recv{
unset req.http.cookie;
}