Configure Apache 2 to Control Browser Caching
In computing, a cache is a component that stores data so future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation, or the duplicate of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store; thus, the more requests can be served from the cache, the faster the system performs.
Caching, as it pertains to hosting a website, is the temporary storage of content. This content could be images, files, bits of PHP scripts that are precompiled, HTML pages, results of database queries, and other web objects.
Step #1: Verify Modules
Apache must be configured with the appropriate modules to leverage browser caching.
Let’s check for mod_expires (expires_module) first:
apachectl -M | grep expires
Then let’s check for mod_headers (headers_module):
apachectl -M | grep headers
Step #2: Examples of Directives
This code can be placed in the .htaccess files for specific directories, or in your root web directory, but we suggest placing it in your httpd.conf.
- The default expiration (ExpiresDefault) is set to 2 days.
- Images expire after 1 month.
- HTML expires after 10 minutes (600 seconds).
Step #3: Implement Directives
The above directives can be implemented easily. If you’re not already, SSH into your server as root. Then edit the httpd.conf file..
Find a section that looks like this:
# Further relax access to the default document root: <Directory "/var/www/html">
The section above (in this case) is the default document root. Add the expiration directives between <Directory “/var/www/html”> and </Directory>.
Then restart Apache
systemctl restart httpd
Full details for mod_expires can be found in the Apache Documentation.