Last Updated:

Browser caching with .htaccess

masonbee
masonbee Development

This is the code I use in my .htaccess files for browser caching with the Apache web server. It is based on code from Robins Blog and uses expires headers and cache control headers. This speeds up the loading time of a website for repeat visitors as the resources are kept in the browsers cache instead of having to be served.

It asks the browser to cache images and video for a year, CSS for a week, javascript for a month and pdfs and flash for a month. 

The only alteration I have made is to add the m4v format to it as that is how my videos are encoded. For another tiny amount of optimisation flash could be removed as no-one really uses it in webdesign anymore.

# BROWSER CACHING USING EXPIRES HEADERS
<IfModule mod_expires.c>
    ExpiresActive On
  
    # Images
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
  
    # Video
    ExpiresByType video/mp4 "access plus 1 year"
    ExpiresByType video/m4v "access plus 1 year"
    ExpiresByType video/mpeg "access plus 1 year"

    # CSS, JavaScript
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"

    # Others
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
</IfModule>

# BROWSER CACHING USING CACHE-CONTROL HEADERS
<ifModule mod_headers.c> 
    # One year for image and video files
    <filesMatch ".(flv|gif|ico|jpg|jpeg|mp4|m4v|mpeg|png|svg|swf|webp)$">
        Header set Cache-Control "max-age=31536000, public"
    </filesMatch>

    # One month for JavaScript and PDF files
    <filesMatch ".(js|pdf)$">
        Header set Cache-Control "max-age=2592000, public"
    </filesMatch>

    # One week for CSS files
    <filesMatch ".(css)$">
        Header set Cache-Control "max-age=604800, public"
    </filesMatch>
</ifModule>
# END BROWSER CACHING USING EXPIRES HEADERS