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 headersto enable headers module and restart server withsystemctl restart apache2after 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-agesets cache keeping duration (measured in seconds),
e.g.Description In seconds Calculation 60 seconds 6060s60 minutes 360060m * 60s24 hours 8640024h * 60m * 60s7 days 6048007d * 24h * 60m * 60s30 days 259200030d * 24h * 60m * 60s12 months 31536000365d * 24h * 60m * 60spublicindicates cache keeping strategy,HTTP 1.1 allows different values to control cache:
publicResources may be cached in public shared caches. privateResources may only be cached in the private cache. no-cacheResources may not be cached. no-storeResources may be cached but not archived.
Note: configuration was tested on Apache 2.4.38 with CloudFlare.
Screenshoot (Google Chrom DevTools):