Hard worker
Hard worker

Reputation: 4046

How do I make Varnish 4 cache everything regardless of cache-control headers and cookies

In a nutshell, I am trying

   if (beresp.ttl < 120s) {
        set beresp.ttl = 120s;
        unset beresp.http.Cache-Control;
      }

In my VCL config file and it's not working. More detail below:

Here is my request header:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:portal1 =dsfgsdfgsdfg; portal1 =sdfgsdfgsdfg; PHPSESSID=randomstring
Host:216.66.35.169
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36

Note that Chrome by default sets Cache-Control of max-age=0 whenever someone enters the url and in the address bar and hits enter I believe. The cookies are the default php one via session_start and also a custom session cookie.

For now I want to ignore the cookies and the cache-control header.

Here is my VCL setup:

sub vcl_recv {
    # Happens before we check if we have this in cache already.
    #
    # Typically you clean up the request here, removing cookies you don't need,
    # rewriting the request, etc.
}

sub vcl_backend_response {
    # Happens after we have read the response headers from the backend.
    #
    # Here you clean the response headers, removing silly Set-Cookie headers
    # and other mistakes your backend does.
   # set beresp.ttl = 60s;


  if (beresp.ttl < 120s) {
    set beresp.ttl = 120s;
    unset beresp.http.Cache-Control;
  }
}

sub vcl_deliver {
    # Happens when we have all the pieces we need, and are about to send the
    # response to the client.
    #
    # You can do accounting or modifying the final object here.

    if (obj.hits > 0) {
                set resp.http.X-Cache = "HIT";
        } else {
                set resp.http.X-Cache = "MISS";
        }
}

The response header is:

Accept-Ranges:bytes
Age:0
Connection:keep-alive
Content-Length:24
Content-Type:text/html
Date:Thu, 27 Aug 2015 13:48:58 GMT
Server:Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8q PHP/5.3.5
Via:1.1 varnish-v4
X-Cache:MISS
X-Powered-By:PHP/5.3.5
X-Varnish:17

Which is a miss.

The php on the backend server is basically just echoing out a random number:

<?php

echo 'Hello worlds';

echo '<hr/>';

echo rand();

?>

Upvotes: 4

Views: 8174

Answers (1)

qux
qux

Reputation: 1165

Cookies are preventing cache hits. Try stripping cookies in vcl_recv and vcl_backend_response.

sub vcl_recv {
    unset req.http.cookie;
}

And in vcl_backend_response

sub vcl_backend_response {


  if (beresp.ttl < 120s) {
      unset beresp.http.cookie;
      unset beresp.http.Set-Cookie;
      set beresp.ttl = 120s;
      unset beresp.http.Cache-Control;
  }

}

Upvotes: 6

Related Questions