Serve dynamicaly generated files from Laravel from the Nginx cache.
# sudo nano /etc/nginx/sites-available/default
fastcgi_cache_path /usr/share/nginx/fastcgi_cache levels=1:2 keys_zone=phpcache:100m max_size=1g inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
location ~ \.php$ {
fastcgi_cache phpcache;
fastcgi_cache_background_update on;
#fastcgi_cache_lock on;
add_header X-FastCGI-Cache $upstream_cache_status;
#...
}
The default web.php
uses cookies. If we want a cached response we can't use cookies.
Create a new middleware group in app/Http/Kernel.php
protected $middlewareGroups = [
'stateless' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
//...
After that create a new stateless.php
file in your routes
folder where all our cachable routes will be loaded. You can add it here app/Providers/RouteServiceProvider.php
.
Route::middleware('stateless')
->namespace($this->namespace)
->group(base_path('routes/stateless.php'));
After that in your route return a response with the Cache-Control headers set.
Route::get('/nginx-cache-test', function () {
sleep(1);
return response('This response was generated at ' . date('H:i:s'))
->header('Cache-Control', 'public, max-age=0, s-maxage=1, stale-while-revalidate=60');
});