Skip to content

Instantly share code, notes, and snippets.

@rolandstarke
Last active June 16, 2022 08:53
Show Gist options
  • Save rolandstarke/2e6975b18aa9056cfaa9b1673cd573ca to your computer and use it in GitHub Desktop.
Save rolandstarke/2e6975b18aa9056cfaa9b1673cd573ca to your computer and use it in GitHub Desktop.
Serve Laravel from the Nginx cache

Nginx FastCGI Cache with Laravel

Serve dynamicaly generated files from Laravel from the Nginx cache.

Nginx config

docs

# 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;
    #...
}

Laravel

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');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment