EN
apache2 - enable files caching (max-age)
12
points
In this short article, we would like to show how to enable cache for website resources (js, css, image, ico and pdf files) inside apache2 VirtualServer
configuration.
The example configuration sets 30 days cache allowing to use publish shared cache (CDNs, etc.).
Quick solution (file /etc/apache2/sites-enabled/my-domain.com.conf
):
<VirtualHost *:443>
ServerName my-domain.com
# some configurations here ...
# 30 days cache on public shared caches
<IfModule mod_headers.c>
<LocationMatch "\.(ico|pdf|jpe?g|png|gif|js|css)$">
Header set Cache-Control "max-age=2592000, public"
</LocationMatch>
</IfModule>
# some configurations here ...
</VirtualHost>
Note: run
a2enmod headers
to enable headers module and restart server withsystemctl restart apache2
after configuration is changed.
Where:
\.(ico|pdf|jpe?g|png|gif|js|css)$
matches files that ends with extensions:ico
,pdf
,jpg
,jpeg
,png
,gif
,js
,css
,
max-age
sets cache keeping duration (measured in seconds),
e.g.Description In seconds Calculation 60 seconds 60
60s
60 minutes 3600
60m * 60s
24 hours 86400
24h * 60m * 60s
7 days 604800
7d * 24h * 60m * 60s
30 days 2592000
30d * 24h * 60m * 60s
12 months 31536000
365d * 24h * 60m * 60s
public
indicates cache keeping strategy,HTTP 1.1 allows different values to control cache:
public
Resources may be cached in public shared caches. private
Resources may only be cached in the private cache. no-cache
Resources may not be cached. no-store
Resources may be cached but not archived.
Note: configuration was tested on Apache 2.4.38 with CloudFlare.
Screenshoot (Google Chrom DevTools):