Controlling The Cache in PHP Using Edge Side Includes in Varnish

If you are using varnish to cache the page in PHP and plan to exclude part of the page from being cached or control it then follow the steps below:

1. Extract the part of the page to be excluded from being cached to a separate file.

Let's assume you want time and date to be excluded from the cache. In this case create a separate php file as below:

// File name: timeDate.php

echo 'Accessed at :' . date('d M Y h:i:sa'); 

2.Include the page using esi tag.

<esi:include src="NoVarnishContent/timeDate" />
<!-- Use esi:remove tag to ensure page is still displayed if esi tag is not enabled! -->
    <div title="This is cached version:">
      <?php include _FILE_ROOT . '/app/views/partials/noVarnishContent/timeDate.php'; ?>

2. Modify the Varnish (/etc/varnish/default.vcl) to enable esi

If you are using varnish above 3.0 then modify vcl_backend_rsponse as below:


sub vcl_backend_response {
    # Step 1: Enable ESI( Edge Side Scripting) to esi:include works
    set beresp.do_esi = true;

   # Step 2: Once we enable do_esi, we need to set ttl for the path that do not need caching. In this case we use wild card to include all the files that follows after NoVarnishContent
    if (bereq.url ~ "NoVarnishContent/*") {
        set beresp.ttl = 0s; # 0s means it won't be cached at all; can set 10s | 1m | 1h and so on
    } else { // for rest of the page
       set beresp.ttl = 30m;
After this, restart the varnish (sudo service varnish restart).