Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn OFF Cache for specific file with Apache

I have a page on a site which uses random() twig, in Firefox and Chrome it is prevented from working because it gets cached as soon as the page loads.

Is there a way to turn off caching of a particular file via the Apache configs, lets call it default.html or even better just turn off caching for the script part of that file but keep caching image files?

I have tried .htaccess but this does not work.

The only way currently that allows the script to work is to turn off caching globally via PHP headers:

<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
?>

But as I only need to turn off caching for an individual page, turning it off for everything seems crazy.

like image 463
Level Avatar asked Jul 09 '15 11:07

Level


People also ask

How do I disable caching in htaccess?

There are times when you must disable caching of your website files. To achieve this, you need a way to force any web browser accessing your site to not cache one or more types of files. For Apache web servers, the best solution is to edit . htaccess to disable caching.

Where is Apache cache stored?

Typically, the cache is stored on disk using the mod_cache_disk module, but shared object caching is also available through the mod_cache_socache module.

Does Apache have a cache?

The Apache HTTP server offers a low level shared object cache for caching information such as SSL sessions, or authentication credentials, within the socache interface. Additional modules are provided for each implementation, offering the following backends: mod_socache_dbm. DBM based shared object cache.


1 Answers

Figured it out, to target a specific file (in this case index.php), add this code to the bottom of .htaccess

<Files index.php>
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</Files>

Alternatively to target a specific selection of files, ie. I'd like to cache images but nothing else (files that match html, htm, js, css, php will not be cached):

<filesMatch "\.(html|htm|js|css|php)$">
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</filesMatch>

To check the .htaccess was being read I entered a few lines of rubbish at the bottom, found out it wasn't being read, renamed it from htaccess to .htaccess and it worked.

like image 142
Level Avatar answered Sep 17 '22 21:09

Level