aidaghazaryan February 2016

set cache headers only when something changed in the website (php, htaccess)

I'm running wordpress. Added this code in .htaccess file so that users will see latest version of website and not the cached one.

<IfModule mod_rewrite.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

But now it loads very slowly and the reason is clear. Cause every time when am refreshing, it loads new files again. I was wondering is there any other way to detect when something had been changed, only then add these headers or clear cache in other way. Don't want to use any plugin. Want to fix it via some php or javascript code. Any help is appreciated.

Answers


Ben February 2016

You can set expires headers for different file extensions like so:

<IfModule mod_expires.c>
  ExpiresActive on

  # Your document html
  ExpiresByType text/html "access plus 0 seconds"

  # Media: images, video, audio
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"

  # CSS and JavaScript
  ExpiresByType application/javascript "access plus 1 year"
  ExpiresByType text/css "access plus 1 year"
</IfModule>

For specific files that you know will be changed on a more regular basis, you can add an extension such as ?=[timestamp] to the URL, so that the browser recognises it as a new version.

For example, you could change the .js file to main.js?version=2 when you want the viewer to see a new version.

Alternatively you can change the extension to main.js?ts=<?php echo date() ?> for the file to be reloaded on every visit, because the timestamp will be different each time.


Edit Another solution would be to use the last-edited time of the file (using filemtime()) to append as a parameter, like so:

<script type='text/javascript' src='main.js?fmt=<?= filemtime("main.js") ?>'>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?ver=' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="all" />

This would mean that the first load after a change in the file's data would force a refresh.

Post Status

Asked in February 2016
Viewed 3,870 times
Voted 9
Answered 1 times

Search




Leave an answer