Control Varnish cache time from php script

883 views Asked by At

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.

0

There are 0 answers