Increase the speed of your website
Nobody is waiting for a slow website, especially if it is a website that you visit more often.
Caching
One of the things you can do to present your website to returning visitors faster is to use caching.
You can use caching in different ways, depending on the web server you are using. Today I'm going to go into more detail about caching for Apache web servers and using .htaccess. Why? Apache is the most used web server worldwide, but a lot of people do not host their website themselves and therefore do not have access to that server. In other words, configuration on the server is impossible. Creating and uploading a .htaccess file is (usually) no problem.
The condition is that the module mod_headers
is activated on the server, which is true in most cases. If not, you can often also ask your hosting company or even switch to another that does not block this.
We start by creating a simple text file that we save as .htaccess – don't forget the dot at the beginning! This file will be placed in the root directory of your website. Below you can find the part of the .htaccess file that is responsible for the caching.
A little explanation. On line 1 we check whether the requested resource is an image, CSS, JavaScript, font … If not, the lines between 1 and 5 are skipped. Then, on line 2, we check if the module mod_headers
is active. This is actually an extra safety check and not strictly necessary, but you never know when someone will deactivate the module. The actual caching takes place on line 3, where we adjust the headers – which a web server sends when a resource is requested. In this case, we set the Cache-Control
with an expiration time of 31,536,000 seconds (one year). public
lets you know that the response may be stored by any kind of cache and must-revalidate
ensures that when the version in the cache becomes obsolete, a validation will first be done on the server before using the version of the cache itself.
More options for Cache-Control
can be found on MDN Web Docs.
GZIP compression
Another way to get your resources to visitors faster is to use GZIP compression. The resource is packed on the server, forwarded and unpacked upon arrival. Compare it to compressing a large image into a ZIP file. Fortunately, this can also be done automatically, with an extra addition to our .htaccess file.
The above first checks whether a particular module (mod_deflate
) is active and then applies the compression to all types of resources that are included. In the list above you will find the general types such as JavaScript, HTML and CSS, but also fonts and SVG files can be included. Be sure to add types yourself if there is a need for your own website.