Search code examples
laravelnginxhttp-headersbrowser-cache

How to force Cache Headers in Laravel


I have a file which I call through the route like this:

Route::group([
    'middleware' => ['cache.headers:public;max_age=600'],
], function () {
    Route::get('/my-file', function ($locale) {
        //some logic

        $contents = 'my file content';
        $response = \Response::make($contents, 200);

        $response->header('Cache-Control', 'public, max-age=600');
        $response->header('Expires', now()->addSeconds(600)->toRfc7231String());
        $response->header('Content-Type', 'application/javascript');
        $response->header('Pragma', '');

        return $response;
    });
});

As you can see, I am applying middleware and passing the headers as I need this file to be cacheable on the device and not served every time back from the server.

On my localhost, this works:

Cache-Control:
max-age=600, public
Connection:
close
Content-Type:
application/javascript
Date:
Thu, 08 Feb 2024 19:23:55 GMT, Thu, 08 Feb 2024 19:23:55 GMT
Expires:
Thu, 08 Feb 2024 19:33:55 GMT
Host:
127.0.0.1:8000
Pragma:

but when I deploy to my live env running on nginx server I get:

Cache-Control:
no-store, no-cache, must-revalidate
Cache-Control:
max-age=600, public
Connection:
keep-alive
Content-Encoding:
gzip
Content-Type:
application/javascript; charset=utf-8
Date:
Thu, 08 Feb 2024 19:17:21 GMT
Expires:
Thu, 19 Nov 1981 08:52:00 GMT
Expires:
Thu, 08 Feb 2024 19:27:21 GMT
Pragma:
no-cache
Pragma:
Server:
nginx/1.14.0 (Ubuntu)

I have tried adjusting the location in nginx conf to set headers there too, but to no avail, still the same thing, and I am not sure how to resolve this. Any help would be appreciated, thanks.


Solution

  • Found the root cause, it was in php.ini ///etc/php/{php-version}/fpm

    find session.cache_limiter = nocache and set to session.cache_limiter =

    then run:

    sudo systemctl restart php7.4-fpm //If you have FastCGI enabled

    and

    sudo systemctl restart nginx

    The php.ini file was overriding any headers I was setting in the app.