Languages
[Edit]
EN

apache2 - enable files caching (max-age)

12 points
Created by:
Blythe-F
650

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 with systemctl 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.
    DescriptionIn secondsCalculation
    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 months31536000365d * 24h * 60m * 60s
  • public indicates 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):

apache2 cache enabled with CloudFlare.
apache2 cache enabled with CloudFlare.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Apache2

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join