0

It is possible in Varnish to use ESI tags to give multiple sections on your page different cache times.

Using varnish 4

For example : index.php

<html>...

<?php  
// Cached as normal in Varnish ( 120 seconds)
 echo " Date 1 (cached): ".date('Y/m/d H:i:s') ."\n";
 ?>

<esi:include src="inc/sidebar.php"/>
<esi:remove>
  <?php include('inc/sidebar.php'); ?>
  <p>Not ESI!</p> 
</esi:remove>

sidebar.php

<?php
 echo "<br>NOT CACHED : ".date('Y/m/d H:i:s');
?>

Config Varnish ( default.vcl)

sub vcl_backend_response { 
  set beresp.do_esi = true;
  ## if sidebar remove cache  else 120 seconds cache 
  if (bereq.url ~ "sidebar.php") { 
     ## set beresp.ttl = 0s; 
     set beresp.uncacheable = true; 
     return(deliver);  
  } else { 
    set beresp.ttl = 120s; 
 }

The above works fine , but I would love to find a way to control this from within my projects. If I get a lot of ESI files this config file would get huge.

I thought about this :

In index.php, as first thing :

<?php
header('Cache-Control: max-age=120');
?>

in sidebar.php

<?php
 header('Cache-Control: max-age=0');
 echo "<br>NOT CACHED : ".date('Y/m/d H:i:s');
?>

In config ( default.vcl )

import std;
sub vcl_backend_response { 
    set beresp.do_esi = true;
# Set total cache time from cache control or 120 seconds.
    set beresp.ttl = std.duration(regsub(beresp.http.Cache-Control, ".*max-age=([0-9]+).*", "\1") + "s", 120s);

    ## Debug , shows up in header.
    set beresp.http.ttl =beresp.ttl;
}

Now this works partially.. If I only put in the header max-age in the index.php , it will control the time this page will get cached. The big problem is that sidebar.php ( max-age=0 ) overwrites all and so the whole page is not cached.

Does anyone know a solution.. The thing that matters is to control cache time ( beresp.ttl ) from within a php script.

Paolo_Mulder
  • 1,233
  • 1
  • 16
  • 28
  • This is a problem with your design. Your include should probably not be sending headers() since headers must be sent prior to any output. You can see how tihs can be a problem as you have includes everywhere. Better have your index.php control the headers, since it knows who it will be included (and then can decide whether to cache the current page). You need to be more clear if your goal is to support partially caching pages (which I don't think it is really). – John Cartwright Jun 11 '15 at 16:13
  • This is about partially caching pages ( or sections of them ) and also control those sections caching times. Not all content needs same caching times. If there was a way to control this from within a project...Instead of the varnish config file. – Paolo_Mulder Jun 11 '15 at 16:18

0 Answers0