Apache Browser Caching: Reference and Examples

Apache Browser Caching: Reference and Examples

Last updated:
Table of Contents

All examples use Apache v2.4 on a debian-like system (e.g. Ubuntu) unless otherwise noted

Cache static assets

These configurations add headers to HTTP responses so that the client browser knows what information it can/should cache. In this example, static files (html, images, etc) are cached.

  • Add this to .htaccess file on your website root

    <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access 1 year"
    ExpiresByType image/jpeg "access 1 year"
    ExpiresByType image/gif "access 1 year"
    ExpiresByType image/png "access 1 year"
    ExpiresByType text/css "access 1 month"
    ExpiresByType text/html "access 1 day"
    ExpiresByType text/x-javascript "access 1 month"
    ExpiresByType application/x-shockwave-flash "access 1 month"
    ExpiresByType image/x-icon "access 1 year"
    ExpiresDefault "access 1 month"
    </IfModule>
    
  • Make sure htaccess files are enabled

    Your VHOST configuration should have a AllowOverride All for the root of your website, or .htaccess files will not even be read.

  • Install/enable mod_expires for apache

    $ sudo a2enmod expires
    $ sudo systemctl reload apache2
    
  • Check configuration did not break the website

    There is no tool (that I know) to test a .htaccess individually, so you should test-load a page on your website to see if the configuration did not break anything

  • Check HTTP headers were added

    Using the sample configuration, PNG images should be cached by the browser for 1 year.

    Try to open a webpage that contains a PNG and see if the headers were correctly set:

    developer-tools-png-cache-image Enable Developer Tools (on Chrome) and
    open a page that contains a PNG image.
    Open tab "Network" and click on a PNG image. If everything is
    set up correctly, you should see Cache control and Expires headers set