9

my php script is sending a header X_Cache_ttl: 1h and in my varnish config file I have

sub vcl_fetch
{
    if(beresp.http.X-Cache-ttl){
            set beresp.ttl = beresp.http.X-Cache-ttl;
    }
}

but the line with the set command is causing varnish to fail when I try to start it.

in the log I get

Expression has type STRING, expected DURATION
('input' Line 116 Pos 34) -- ('input' Line 116 Pos 56)
            set beresp.ttl = beresp.http.X-Cache-ttl;

How do I convert X-Cache-ttl to a duration so that I can dynamically set the TTL?

I would like to avoid multiple if statements similar to

if(beresp.http.X-Cache-ttl == "60s") {
    set beresp.ttl = 60s;
}

if(beresp.http.X-Cache-ttl == "1h") {
    set beresp.ttl = 1h;
}

If it matters I'm using varnish 3.0.3 on centos 6.

DiverseAndRemote.com
  • 2,091
  • 3
  • 16
  • 16
  • I encountered same roadblock. Did you find any work-around for varnish 3.x or even 2.1.5 for that matter? At the moment, I have 2.1.5 on production and 3.x on a staging. Cannot move to ver 4.x because it's syntax is vastly different and our VCL is a bit complicated to move to new version immediately. – anup Mar 06 '17 at 07:38

2 Answers2

11

The vmod_std module has a function that should do what you're looking for.

import std; at the top of the VCL, then this should work:

sub vcl_fetch
{
    set beresp.ttl = std.duration(beresp.http.X-Cache-ttl, 1h);
}

..where the 1h is your default if the header isn't set.

Shane Madden
  • 114,520
  • 13
  • 181
  • 251
2

According to the Varnish documentation you can use the Cache-Control header.

Cache-Control

The 'Cache-Control' header instructs caches how to handle the content. Varnish cares about the max-age parameter and uses it to calculate the TTL for an object.

So make sure you issue a 'Cache-Control' header with a max-age header. You can have a look at what Varnish Software's Drupal server issues:

$ GET -Used http://www.varnish-software.com/|grep ^Cache-Control
Cache-Control: public, max-age=600

https://github.com/varnishcache/varnish-cache/blob/master/doc/sphinx/users-guide/increasing-your-hitrate.rst

wiktor
  • 121
  • 2