Search Our Database

How to prevent HTTP file caching with .htaccess

Last updated on |
under |
by

Introduction

This guide is designed for web developers and server administrators who want to prevent browsers from caching outdated versions of CSS and JavaScript files. By using .htaccess you can ensure that visitors always see the latest version of your website’s styles and scripts, especially after updates.

These steps are useful when frequent updates are made to the site, and caching causes display issues or functionality problems. The guide is applicable to Apache servers where .htaccess files are used to control server behavior.

 

Prerequisites

  • Basic knowledge of Linux terminal
  • Access to the server
  • Permission to edit or create an .htaccess within the web server directory

 

Steps

  1. Login to the server via SSH access.
  2. Use the cd command to navigate to the web directory file and use the ls command to list down all the file in the directory.

cd /var/www/html 
ls -asl

3. If an .htaccess file already existed, you can use the open the file and edit it right away. If none, therefore, you will need to create new .htacess file.You can use touch command to create the .htaccess file.

touch /var/www/html/.htaccess

 

4. Change the file permissions as well to ensure it is writeable by Apache

chown apache /var/www/html/.htaccess

 

5. Use vi  command to open and edit the file

vi /var/www/html/.htaccess

 

6. Add the following code to the .htaccess file to prevent caching of CSS, JavaScript, and HTML files:

<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>

 

7. Save and exit the file. The .htaccess file now ensure that your website’s CSS, JavaScript, and other specified file are not cached by web browsers.

 

 

Conclusion

By following the steps outlined in this guide, you have successfully configured your Apache server to prevent the caching of CSS and JavaScript files. This ensures that any updates you make to your site will be immediately visible to users, improving consistency and eliminating potential confusion caused by outdated files.

 

Article posted on 26 March 2020.

 

Dedicated Server from RM549/mth!

Check out IPServerOne’s Dedicated Server Packages.
Contact us @ +603-2026-1688 or email @ sales@ipserverone.com