Varnish cache, How to cache static content
1 min read

Varnish cache, How to cache static content

Varnish cache, How to cache static content

There is a lots of proxy cache options out there but fastest one of those is Varnish cache.The default configuration comes with barebones options with default.vcl. You can edit default.vcl file and add these following options to cache static content.

sub vcl_recv {
	if (req.url ~ ".*\.(?:css|js|jpe?g|png|gif|ico|swf)(?=\?|&|$)") {
	unset req.http.Cookie;
	return (hash);
	}
}
sub vcl_backend_response {
    if ((bereq.url ~ "\.(css)(?=\?|&|$)" && beresp.http.Content-Type ~ "text/css")
        || (bereq.url ~ "\.(jpe?g|png|gif|ico)(?=\?|&|$)" && beresp.http.Content-Type ~ "image/")
        || (bereq.url ~ "\.(js)(?=\?|&|$)" && beresp.http.Content-Type ~ "javascript")
        || (bereq.url ~ "\.(swf)(?=\?|&|$)" && beresp.http.Content-Type ~ "application/x-shockwave-flash")
        || (bereq.url ~ "\.(woff)(?=\?|&|$)" && beresp.http.Content-Type ~ "font")) {
	set beresp.ttl = 28800s; #The number of seconds to cache inside Varnish
	set beresp.http.Cache-Control = "max-age=28800"; #The number of seconds to cache in browser
	}
}

After these you can reload your vcl or restart your varnish.You can check your page with your favorite browser's developer tools and look for headers of your static content and check x-varnish key.After a page reload it will show multiple ids and you are good to go.