Maria
Maria

Reputation: 9

How to avoid browser caching of CSS, JS and image files using .htaccess?

RewriteCond %{REQUEST_URI} ^/[images|css|js]/
RewriteRule ^/(.*)$ /$1?ver=2 [L]

Now am using this code. But its not working.

Upvotes: 0

Views: 3966

Answers (2)

user4655002
user4655002

Reputation:

A few other options too:

Browser hard refresh (Chrome)

Ctrl + F5 (or Ctrl + refresh button)

Time stamp after the CSS files (instead of time, use some sort of version control)

<script src="myjsfile.js?t=<?php echo time(); ?>"></script>

HTML meta no cache

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

.Htaccess (thanks to top answer here: How to prevent http file caching in Apache httpd (MAMP))

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     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"
  </ifModule>
</filesMatch>

Upvotes: 1

roberto06
roberto06

Reputation: 3864

Htaccess solution :

You might want to use mod_headers functions Cache-Control and Expires, for the file types you want the browser to not cache :

<filesMatch "\.(js|css|jpg|jpeg|png|gif)$">
FileETag None
<ifModule mod_headers.c>
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"
</ifModule>
</filesMatch>

Source

PHP solution :

You could also load each resource with a different timestamp each time your page is shown :

 <script type="text/javascript" src="myfile.js?time=<?php echo mktime(); ?>" />
 <link rel="stylesheet" media="screen" href="/myfile.css?time=<?php echo mktime(); ?>">

Upvotes: 1

Related Questions