Laravel • Varnish • Performance
by Dimitri König Reading time: ~8 minutes

3 simple ways on how to get started with caching in Varnish Cache

2 factors to consider and 3 ways to choose from to get started with caching in Varnish

  1. Do you have complete control over your Varnish configuration AND/OR do you have complete control over your application?
  2. Is your website (mostly) static or dynamic? Does it have pages behind a user login? Or is it using sessions even for guests?

Depending on the answers there are 3 simple ways on how to get started with caching in Varnish.

1. Caching using only headers from backend server and application

If you have full control over only your application, then this could be a starting point.

Usually Varnish Cache is given some cache header information from the backend application which it uses to handle caching. And indepth tutorial at the Varnish Developer Portal about Http caching basics is all about how Varnish interprets those caching headers.

In Varnish you keep your configuration very simple and allow the application to tell Varnish what to cache and how to cache.

In your application you need to send caching headers with the response. In Laravel, with a default configuration, sessions are used and therefore every response contains explicit no-cache headers: Cache-Control: "no-cache, private". To send cache headers you have to remove your session middleware and add the core cache header middleware to those routes you want to cache:

3// routes/web.php
5Route::withoutMiddleware([StartSession::class, ShareErrorsFromSession::class, VerifyCsrfToken::class])
6 ->middleware('cache.headers:public;s_maxage:3600')
7 ->group(function () {
8 Route::view('/', 'welcome');
9 });

Here you instruct Varnish to cache the root route for 1h.

Fore more information on this approach you can checkout slides for the Laracon EU 2022 presentation by Thijs Feryn.

But if you use cookies for sessions (store data temporarily, let users log in), you need another approach:

2. Caching using PARTLY headers from backend server and application, and PARTLY Varnish logic

If you have some sort of user login, you first need to implement some business logic mentioned in my article about avoiding showing user specific information by wrongful caching.

For this to work you need some control/influence over your Varnish configuration (just a little) and be able to implement some changes on your application to make it work.

Then, for a simple start, you can use Spatie's Varnish package to add caching headers without removing any middleware like in the previous step, which could look like this:

1// routes/web.php
3// Will be cached by Varnish for a default time of 24h
4Route::group(['middleware' => 'cacheable'], function() {
5 Route::get('/', 'HomeController@index');
6 Route::get('/contact', 'ContactPageController@index');
9// Varnish will cache the responses of the routes inside the group for 15 minutes
10Route::group(['middleware' => 'cacheable:15'], function() {
11 ...
14// won't be cached by Varnish at all since specific cache headers are missing
15Route::get('do-not-cache', 'AnotherController@index');

Your final simple Varnish configuration then would look like this:

1vcl 4.1;
3# Default backend definition. Set this to point to your content server, for example Nginx, which retrieves static files, passes data through to PHP, etc...
4backend default {
5 .host = "";
6 .port = "8080";
9sub vcl_recv {
10 if (req.http.Cookie ~ "(?i)(loggedin)") {
11 return (pass);
12 }
14 if (req.url ~ "(?i)(do-not-cache)") {
15 return (pass);
16 }
18 unset beresp.http.set-cookie;
20 return (hash);
23sub vcl_backend_response {
24 if (beresp.http.X-Cacheable ~ "1") {
25 unset beresp.http.set-cookie;
26 }

3. Caching using ONLY Varnish logic

If you know for sure that you have certain pages which never are allowed to be cached but others should (always) be cached, you can setup Varnish in such a way that you don't need to modify your application at all. This blog uses this method since it's very predictable what should be cached and what shouldn't.

The way to go is defining how requests will be processed by categorizing them right when they come in (setting "X-Cache-Mode" in vcl_recv) and how they will be stored (vcl_backend_response).

For better understanding you can proceed by reading this Varnish configuration and the comments in it:

1sub vcl_recv {
2 # you start by defining that the default case is always uncachable to make sure you don't get any false positives
3 set req.http.X-Cache-Mode = "uncachable";
5 # urls with certain file extensions or from certain folders will be marked as static
6 if (req.url ~ "^[^?]*\.(css|map|gif|ico|jpeg|jpg|js|png|svg|txt|webm|webp|woff|woff2|xml)(\?.*)?$" || req.url ~ "^/(storage|vendor|build|css|js|images)/") {
7 unset req.http.cookie;
8 set req.url = regsuball(req.url, "\?.*$", "");
10 set req.http.X-Cache-Mode = "static-file";
12 return (hash);
13 }
15 # don't cache big static files, just stream them
16 if (req.url ~ "^[^?]*\.(7z|avi|bz2|flac|flv|gz|mka|mkv|mov|mp3|mp4|mpeg|mpg|ogg|ogm|opus|rar|tar|tgz|tbz|txz|wav|webm|xz|zip|pdf)(\?.*)?$") {
17 unset req.http.Cookie;
18 set req.http.X-Cache-Mode = "static-file-stream";
20 return (pass);
21 }
23 # bypass admin pages, preview pages, auth pages, etc...
24 if (req.url ~ "/admin"
25 || req.url ~ "/preview"
26 || req.url ~ "/auth"
27 )
28 {
29 set req.http.X-Cache-Mode = "bypass";
31 return (pass);
32 }
34 # avoid delivering any content from cache if logged in. but only at this point, to make sure that static files are delivered from cache
35 if (req.http.Cookie ~ "(?i)(loggedin)") {
36 set req.http.X-Cache-Mode = "bypass";
37 return (pass);
38 }
40 # if this point has been reached then you are in (mostly) static territory, so remove cookies to make sure that this request gets cached
41 unset req.http.cookie;
43 # here you have only 3 types of pages: home, articles and the rss feed. everything else does not need to even be passed over to the application since it will always result in a 404.
44 # helps a lot with bad bots and script kiddies
45 if (req.url != "/" && req.url !~ "^/articles/" && req.url != "/feed") {
46 return (synth(404, "Not found"));
47 }
49 # at this point you can assume that you are dealing with static content only
50 set req.http.X-Cache-Mode = "static-content";
52 return (hash);
55# here you process all the request coming back from your backend, be it static files or content from your application
56sub vcl_backend_response {
57 # to make sure we can see in response headers what mode has been set, for debugging purposes only
58 set beresp.http.X-Cache-Mode = bereq.http.X-Cache-Mode;
60 # Never cache 50x responses
61 if (beresp.status == 500 || beresp.status == 502 || beresp.status == 503 || beresp.status == 504) {
62 return (abandon);
63 }
65 # if it's content that should not be cached, return right away without any further processing
66 if (bereq.http.X-Cache-Mode == "uncachable" || bereq.http.X-Cache-Mode == "bypass")
67 {
68 return (deliver);
69 }
71 # Large static files should be streamed and never cached
72 if (bereq.http.X-Cache-Mode == "static-file-stream") {
73 unset beresp.http.set-cookie;
74 set beresp.do_stream = true;
76 return (deliver);
77 }
79 # at this point we should have only x-cache-mode == "static-content" and "static-file" stuff, so cache them for 7 days
80 if (bereq.http.X-Cache-Mode == "static-file" || bereq.http.X-Cache-Mode == "static-content") {
81 set beresp.ttl = 7d;
83 # important: make sure that the browser does not cache content as well, otherwise the browser cache would take precedence
84 set beresp.http.Cache-Control = "no-cache, private";
86 unset beresp.http.set-cookie;
88 return (deliver);
89 }
91 return (deliver);

Debugging tip

If you want to see how Varnish interprets these headers, you can set some additional debugging headers. First you want to know how Varnish interprets those caching headers it receives from its backend:

1sub vcl_backend_response {
2 set beresp.http.X-Original-TTL = beresp.ttl;

This way you know what time-to-live (TTL) Varnish has initialy interpreted. But that is only for the initial backend fetch. Afterwards, when Varnish stores the object, upon delivery, you can see additional information about its current state, like wether its being delivered from cache (HIT) or from the backend (MISS), how many successful requests from cache (X-Cache-Hits) already haven been made, and the remaining TTL until the object expires (X-Cache-Remaining-TTL).

1sub vcl_deliver {
2 if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS and the number of hits, disable when not needed
3 set resp.http.X-Cache = "HIT";
4 set resp.http.X-Cache-Hits = obj.hits;
5 set resp.http.X-Cache-Remaining-TTL = obj.ttl;
6 } else {
7 set resp.http.X-Cache = "MISS";
8 }

Cache invalidation

Caching is actually the easy part. Cache invalidation is the tricky part. The most easy way to do this is on any content change just to purge everything and start all over (maybe even with a warmup script). The simple way is to purge by url. And in some cases you may even need to purge by tags. But that's for another article.

Feel free to comment on Twitter: