Caching requests by HTTP status code

Loading

Sometimes you may want to cache request based on the status code with a different TTL.

Adding the following in the vcl_backend_response will help you in achieving the result:


if (beresp.status == 403 || beresp.status == 404 || beresp.status >= 500)
{
   set beresp.ttl = 60s;
}

Force cache and leverage browser caching for non cachable contents

Loading

Add this code in the VCL_BACKEND_RESPONSE:


sub vcl_backend_response {

  # client browser and server cache
  # Force cache: remove expires, Cache-control & Pragma header coming from the backend
  if (beresp.http.Cache-Control ~ "(no-cache|private)" || beresp.http.Pragma ~ "no-cache")  {
     unset beresp.http.Expires;
     unset beresp.http.Cache-Control;
     unset beresp.http.Pragma;
              
     # Marker for vcl_deliver to reset Age: /
     set beresp.http.magicmarker = "1";
     
     # Leveraging browser, cache set the clients TTL on this object /
     set beresp.http.Cache-Control = "public, max-age=2592000";
	 
     # cache set the clients TTL on this object /        
     set beresp.ttl = 30d;  

     # Allow stale content, in case the backend goes down.
     # make Varnish keep all objects for 6 hours beyond their TTL
     set beresp.grace = 6h;
     return (deliver);
  }

}

Also add this in the VCL_DELIVER:


sub vcl_deliver {
# Called before a cached object is delivered to the client.
	
  if (resp.http.magicmarker) {
	unset resp.http.magicmarker;
	# By definition we have a fresh object 
	set resp.http.Age = "0";
	}
    
  if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS and the number of hits, disable when not needed
    set resp.http.X-Cache = "HIT";
  } else {
    set resp.http.X-Cache = "MISS";
  }
  # Please note that obj.hits behaviour changed in 4.0, now it counts per objecthead, not per object
  # and obj.hits may not be reset in some cases where bans are in use. See bug 1492 for details.
  # So take hits with a grain of salt
  set resp.http.X-Cache-Hits = obj.hits;
  
  # Set Varnish server name
  set resp.http.X-Served-By = server.hostname;

  # Remove some headers: PHP version
  unset resp.http.X-Powered-By;

  # Remove some headers: Apache version & OS
  unset resp.http.Server;
  unset resp.http.X-Varnish;
  unset resp.http.Via;
  unset resp.http.Link;
  unset resp.http.X-Generator;

  return (deliver);
}