Htaccess Leverage Browser Caching

HTACCESS Leverage Browser Caching

Today I’m going to share a short code snippet. The htaccess Leverage Browser Caching code snippet. If you’ve reached his page that means you want to leverage browser caching using code. I will assume you know your way around.

leverage browser caching .htaccess

There are several ways of leveraging a browser cache. However, be advised, if you are using some sort of a CMS(for instance: WordPress) you might have an optimization plugin that does this for you. In this case, this snippet is not necessary for you.
Furthermore, before making any changes to the .htaccess file, please make a backup of the mentioned file. an htacesss file is a critical component in any system. It’s one of Apache’s configuration files. Apache is a web-server, any error in the mentioned file will crash your website. Don’t say I didn’t warn you!

<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/mpeg "access plus 1 year"
  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 month"
  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"

The code snippet above sets the recommended settings for browser caching. In short, what the code above does, it tells the web browser to send a directive to the user’s browser to cache the following parameters(for instance: images) for a pre-defined time duration. Resulting in a situation that reduces server HTTP requests to fetch resources and assets, And finally, reduces page loading times!

Final Words

I hope the snippet above helped you. However keep in mind, if your website uses nginx as a web-server the following bit of code won’t help. In addition to that, nginx doesn’t even have an Htaccess file. Meaning, things work differently there. a future equivalent code snippet article will be published soon. Moreover, nowadays you simply must leverage browser caching, no matter how you do it, just do it(plugin/code).
Finally, if you want to read more about the .htaccess file and its capabilities, visit here: Apache HTTP Server Tutorial: .htaccess files
For more code snippets, click here: Code Snippets

Leave a Reply

Your email address will not be published. Required fields are marked *