Leverage Browser Caching – How to turn it on

Apache logo - leverage browser caching

So! If you’re a web developer like me, you unfortunately have to bow before performance reports from GTMetrix, Google’s PageSpeed Insights, and still-in-beta web.dev.

Don’t get me wrong, the stuff they find are mostly good things, like making your site more accessible and noticeably speedier. But sometimes it can feel like you’re just running in circles to appease these almighty tests.

Anyway, one if the issues that popped up on site after site over the years that i finally got fed up with was the “leverage browser caching” section. I needed to do something about it—finally.

Dreaded GT Metrix "leverage browser caching"

Here’s what i found to leverage browser caching on an Apache server. Hopefully this will save you an hour’s worth of time.

First, we need to check if these modules are enabled: mod_headers.c and mod_expires.c. Run the apache2 -l command to list the enabled modules. You should get something like

[email protected]:~$ apache2 -l
Compiled in modules:
  core.c
  mod_so.c
  mod_watchdog.c
  http_core.c
  mod_log_config.c
  mod_logio.c
  mod_version.c
  mod_unixd.c

Run sudo a2enmod headers expires to enable both mod_headers.c and mod_expires.c. You’ll then need to restart apache — sudo service apache2 restart. Once i’ve done that, i like to try enabling them again, and if i get the response below, i know all is good.

[email protected]:~$ sudo a2enmod headers expires
Module headers already enabled
Module expires already enabled

Next is to edit your .htaccess file. This way is for a per site basis, hence adding the code in my gist to the site’s.htaccess.

You could accomplish this server-wide via VirtualHost configuration file sudo vim /etc/apache2/sites-enabled/000-default.conf by adding code found on a Digital Ocean guide.

And you should be good. To enable gzip compression — another item on these performance reports — check out my other piece on gzip compression.

If you found this post useful ...

Buy Me a Coffee logo
Wondering why you keep seeing lower-cased 'i' in my posts? Read -> Why ‘i’ is not capitalized

2
Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
trackback

[…] sure to check out the two sister posts on leveraging browser caching and gzip […]

trackback

[…] I hope that helps! Oh, and make sure you check out my post on how to leverage browser caching. […]