To solve the issue of Cloudflare not caching your images due to cookies being set by Laravel, you can create a custom middleware group specifically for your image routes that excludes any middleware that manipulates cookies. Here's how you can do it:
-
Create the Middleware: It looks like you've already created a middleware
RemoveCookieHeadersthat removes theSet-Cookieheaders. Ensure it's correctly implemented as shown in your question. -
Define a New Middleware Group: Instead of adding your
RemoveCookieHeadersmiddleware to the global middleware stack or thewebgroup, create a specific group for your image routes that does not include cookie or session handling middleware. -
Modify
Kernel.php: In yourapp/Http/Kernel.php, define a new middleware group for your image routes. Here's how you can set it up:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'images' => [
\App\Http\Middleware\RemoveCookieHeaders::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
-
Apply the Middleware Group to Routes: In your routes file (typically
web.phpor a separate routes file if you prefer), apply this new middleware group to your image routes:
Route::group(['middleware' => ['images']], function () {
Route::get('/image/{filename}', 'ImageController@show');
});
-
Adjust Your Controller: Ensure your
ImageController@showmethod handles the logic for serving images, potentially including any dynamic cropping or other manipulations before the response is sent. -
Test Your Setup: After implementing these changes, test your image routes to ensure that no cookies are being set and that Cloudflare can cache these responses.
This setup ensures that your image-serving routes are isolated from the default web middleware stack that includes cookie and session handling, thus allowing Cloudflare to cache the images as there are no cookies that would otherwise instruct Cloudflare to bypass caching.