Caching-Laravel-HTML-With-Cloudflare

哪里会有人喜欢孤独,不过是不喜欢失望

If you’re serving any sort of content site with Laravel, you’ve probably looked into setting up caching for your page responses. For this site owenconti.com, I’m letting Cloudflare handle the caching for me. I do this by setting up a Page Rule to “cache everything”:

The above page rule will cache everything that the Laravel app returns. However, Cloudflare does not cache responses that modify cookies. By default, Laravel’s web middleware is setup to handle sessions for you.

Removing Session Middleware

Since this site is purely for anonymous visitors, I’ll never need to use sessions or cookies of any sort. Because of that, I am able to remove all of the session and cookie middlewares from the web middleware group:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// app\Http\Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
protected $middleware = [
// ...
];

/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class, //
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],

'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];

After removing the session and cookie middlewares, Cloudflare will start to properly cache HTML responses from the Laravel application.

You can validate this by checking the response headers of the HTML response:

1
2
3
cache-control: public, max-age=3600, s-maxage=86400
cf-cache-status: HIT
cf-ray: 6803f1964956e472-SEA

https://owenconti.com/posts/caching-laravel-html-with-cloudflare