Caching: Cache-Control header

Leon Fayer
Web Performance for Developers
2 min readNov 13, 2017
Amazonia, Peru © Leon Fayer

The easiest way to ensure that your web requests are going to be cached by front end consumers, such as browsers, mobile devices and proxies, is to defined Cache-Control header for all the resources that you serve.

At the most basic level, all you have to do is add one line to your .htaccess file (if you’re using Apache):

# cache all resources for one month
Header set Cache-Control “max-age=2628000, public”

This will direct front end consumers to, much like the comment says, cache all the pages and files you serve for a month. So if a user hits your webpage and returns to it tomorrow, that request will not hit your server, but rather be served from the browser cache.

That’s great and all, but chances are, your site is serving dynamic content that changes a little more frequently than once a month. So perhaps you want to put some logic around the caching directives to differentiate the content and TTL for different types of files.

# cache static assets for one month
<filesMatch “.(jpg|jpeg|png|gif|js|ico)$”>
Header set Cache-Control “max-age=2628000, public”
</filesMatch>

In this example, the directive is to cache only images for one months. Other types of files will be served without cache directives.

You can add more complex rules, such as setting cache directives for individual files and determining TTL on them based on the volatility of the content served.

You can also define header directly inside your application pages, to add even more granularity and flexibility for offloading content serving on to the consumers. For example, if you’re using PHP, you can add a header directly into an individual page:

# cache this page for one minute
<? header(“Cache-Control: max-age=60”); ?>

And for those thinking that one minute cache is not going to help much, think again!

--

--

Leon Fayer
Web Performance for Developers

Technologist. Cynic. Of the opinion that nothing really works until it works for at least a million of users.