How to use Varnish to speed up my Website

Because Symfony2’s cache uses the standard HTTP cache headers, the Symfony2 Reverse Proxy can easily be replaced with any other reverse proxy. Varnish is a powerful, open-source, HTTP accelerator capable of serving cached content quickly and including support for Edge Side Includes.

Configuration

As seen previously, Symfony2 is smart enough to detect whether it talks to a reverse proxy that understands ESI or not. It works out of the box when you use the Symfony2 reverse proxy, but you need a special configuration to make it work with Varnish. Thankfully, Symfony2 relies on yet another standard written by Akamaï (Edge Architecture), so the configuration tips in this chapter can be useful even if you don’t use Symfony2.

Note

Varnish only supports the src attribute for ESI tags (onerror and alt attributes are ignored).

First, configure Varnish so that it advertises its ESI support by adding a Surrogate-Capability header to requests forwarded to the backend application:

sub vcl_recv {
    set req.http.Surrogate-Capability = "abc=ESI/1.0";
}

Then, optimize Varnish so that it only parses the Response contents when there is at least one ESI tag by checking the Surrogate-Control header that Symfony2 adds automatically:

sub vcl_fetch {
    if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
        unset beresp.http.Surrogate-Control;

        // for Varnish >= 3.0
        set beresp.do_esi = true;
        // for Varnish < 3.0
        // esi;
    }
}

Caution

Compression with ESI was not supported in Varnish until version 3.0 (read GZIP and Varnish). If you’re not using Varnish 3.0, put a web server in front of Varnish to perform the compression.

Cache Invalidation

You should never need to invalidate cached data because invalidation is already taken into account natively in the HTTP cache models (see Cache Invalidation).

Still, Varnish can be configured to accept a special HTTP PURGE method that will invalidate the cache for a given resource:

sub vcl_hit {
    if (req.request == "PURGE") {
        set obj.ttl = 0s;
        error 200 "Purged";
    }
}

sub vcl_miss {
    if (req.request == "PURGE") {
        error 404 "Not purged";
    }
}

Caution

You must protect the PURGE HTTP method somehow to avoid random people purging your cached data.