Increase your websites' performance on Apache with caching using htaccess
Caching is a fundamental method for improving the performance of an application. Even if you did not yet implement it explicitly, caching is always present on lower layers of the system. For example, the page cache used by Linux to decrease access times on files and folders. Caching is always a trade-off between the currency of the cached files, the performance gain and the additional space that is required to store the cached files. For that reason we should not just cache everything for the sake of that we implemented a cache, but think about the files and assets that make sense to be cached first.
What to cache?
First of all, we analyze our website using a tool like the Chrome developer tools or the Firefox Developer Edition. We do this to get an overview of the assets that have an impact on the load time of our website. The image below shows all files that are loaded when accessing Twitter.
In most cases, images and other media files make the major part of the size of a website. Caching images on the client side can dramatically boost the loading time of a website. Specially, users who access our website with a mobile device while they are connected with a cellular network profit from reduced data transfer and faster loading.
Fonts are the last elements that we want to consider here. Nowadays, custom fonts are used in almost every modern website. However, many tutorials that I’ve read about website performance don’t take fonts into account. In fact, fonts can definitely impact the loading time of a website, or even block the whole site from rendering. By default, a browser sees a stylesheet as a render blocking ressource. If the stylesheet contains a font that can not be loaded, the browser will continue to render your page. Therefore, you should make sure to load fonts only from reliable sources. But since we don’t change the font of our website frequently, we should cache them anyhow.
How to cache?
We will use the Apache module mod_expires to enable the caching of our elements. The module needs to be loaded via the server configuration file. Unfortunately (or fortunately), most web hosters will not allow you to directly manipulate the server config file. However, the expire module is usually enabled by most hosters. In this case, we can easily enable caching via .htaccess as shown below: