What is caching?
Caching (pronounced “cashing”) is the process of storing data in a cache. – Margaret Rouse – whatis.com
So if caching is storing data in a cache, then what is a cache?
This has two beneficial effects:
- The website loads faster for the user.
- The server doesn’t have to be bothered by any unnecessary traffic.
So how do I start caching my static resources?
Note: This tutorial is for XAMPP server installations only.
In order to be able to start caching resources on an apache server you need to make sure of a couple of things.
- Make sure the mod_expires module is installed and turned on in your apache server configuration.
- Make sure the mod_headers module is installed and turned on in your apache server configuration.
- Make sure your hosting company allows you to use a .htaccess file.
You can contact your hosting company and they will be able to give you more information about whether or not you’re allowed to have these modules turned on and whether you can use an .htaccess file.
The .htaccess code
Credit for the code snippet below should go to Charles Torvalds from askapache.com
NOTE: The lines starting with an # are comments meant to explain the code written below it.
# Turn on Expires and set default to 0 ExpiresActive On ExpiresDefault A0 # Set up caching on media files for 1 year (forever?) ExpiresDefault A29030400 Header append Cache-Control "public" # Set up caching on media files for 1 week ExpiresDefault A604800 Header append Cache-Control "public" # Set up 2 Hour caching on commonly updated files ExpiresDefault A7200 Header append Cache-Control "proxy-revalidate" # Force no caching for dynamic files ExpiresActive Off Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform" Header set Pragma "no-cache"
- Use expires instead of Cache-control: max-age (expires is more widely supported)
- Set expires to a minimum of one month for static resources.
- Don’t set expires more than one year into the future.(It violates the RFC guidelines).
- Set last-modified to the last date the resource was changed.
Here’s a good list of resources to help you on your way: