Skip to content

HTTP caching on Apache with mod_cache and mod_cache_disk

Server-side response caching on Apache with mod_cache — disk vs shared memory, the right CacheEnable scope, and the headers that control freshness.

mod_cache lets Apache act as its own HTTP cache for upstream-generated responses — saving disk-served copies of pages that the upstream marked cacheable, and serving them on subsequent requests without round-tripping. Done right, it cuts upstream load by an order of magnitude on read-heavy sites. Done wrong, it serves stale pages to logged-in users or caches Set-Cookie headers across sessions. This article is the safe-by-default configuration and the headers that make it work.

How to verify

Confirm modules and whether anything is being served from the cache:

apachectl -M | grep -E 'cache|expires|headers'
grep -rE 'CacheEnable|CacheRoot' /etc/apache2/sites-enabled/ /etc/apache2/conf-enabled/
ls -la /var/cache/apache2/mod_cache_disk/ 2>/dev/null | head
curl -sI https://example.com/ | grep -iE 'cache-control|x-cache|age'

X-Cache is not a default header but is convenient — add Header set X-Cache "HIT-or-MISS" via mod_cache configuration with CacheDetailHeader on. The Age: header (added by mod_cache to cached responses) shows how long the response has been in the cache.

What’s happening

mod_cache is a hook that sits in the request handling chain. On a request, it checks whether a cacheable response exists for the URL; if yes, it serves it (subject to freshness rules) and the upstream is never consulted. If no, the request flows through to the application, and on the way back mod_cache decides whether to store the response based on the response headers.

Two storage backends:

  • mod_cache_disk — files on disk. Good for large caches, survives restarts, but I/O bound.
  • mod_cache_socache — shared memory cache (using mod_socache_*). Fast, but bounded by RAM and lost on restart.

Most sites use mod_cache_disk for the long tail and skip socache; it’s simpler operationally.

The cacheability decision is governed by HTTP semantics:

  • A response with Cache-Control: no-store or Cache-Control: private is not cached.
  • A response with Set-Cookie is not cached unless CacheStoreNoStore On and similar overrides.
  • A response with Vary: Cookie is keyed by the request’s Cookie: header — typically uncacheable in practice.
  • A response with a non-2xx status and no Expires/max-age is typically not cached.
  • A POST/PUT/DELETE response is not cached.

This means upstream applications that want their responses cached must set headers like Cache-Control: public, max-age=300 on cacheable responses.

The procedure

  1. Enable the modules.

    sudo a2enmod cache cache_disk expires headers
    sudo apache2ctl configtest
    sudo systemctl reload apache2
  2. Configure mod_cache_disk globally. Create /etc/apache2/conf-available/mod_cache.conf:

    <IfModule mod_cache_disk.c>
        CacheRoot              /var/cache/apache2/mod_cache_disk
        CacheDirLevels         2
        CacheDirLength         1
        CacheMaxFileSize       1048576
        CacheMinFileSize       1
        CacheReadSize          0
        CacheReadTime          0
    </IfModule>
    
    <IfModule mod_cache.c>
        CacheQuickHandler      off
        CacheLock              on
        CacheLockPath          /tmp/mod_cache-lock
        CacheLockMaxAge        5
    
        CacheIgnoreHeaders     Set-Cookie
        CacheIgnoreCacheControl off
        CacheIgnoreNoLastMod    off
    
        CacheDetailHeader on
        CacheHeader on
    </IfModule>

    CacheQuickHandler off runs the cache later in the request lifecycle — slower but allows mod_rewrite and mod_auth rules to fire before the cache hit. The “on” variant is faster but skips authentication, which can serve restricted content publicly.

    CacheLock on prevents the “thundering herd” — when a cached response expires and N concurrent requests arrive, only one goes to the upstream and the rest wait for the result.

  3. Enable caching per-vhost or per-location. The CacheEnable directive is the trigger:

    <VirtualHost *:443>
        ServerName example.com
    
        <Location /static>
            CacheEnable disk
            # Override upstream Cache-Control if missing
            ExpiresActive On
            ExpiresDefault "access plus 1 hour"
        </Location>
    
        <Location /api>
            # Skip cache on the API
            CacheDisable on
        </Location>
    </VirtualHost>
  4. Configure expires for upstreams that do not set Cache-Control. Some upstreams (legacy PHP apps, static-file servers) do not emit good cache headers. mod_expires adds them:

    ExpiresActive On
    ExpiresByType text/css                 "access plus 1 month"
    ExpiresByType application/javascript   "access plus 1 month"
    ExpiresByType image/png                "access plus 1 month"
    ExpiresByType image/jpeg               "access plus 1 month"
    ExpiresByType image/svg+xml            "access plus 1 month"
    ExpiresByType font/woff2               "access plus 1 year"
    ExpiresByType text/html                "access plus 5 minutes"
  5. Enable and reload.

    sudo a2enconf mod_cache
    sudo apache2ctl configtest
    sudo systemctl reload apache2
  6. Verify hits and misses. With CacheDetailHeader on, responses include an X-Cache-Detail header showing why the cache decision was made. Watch the cache hit ratio:

    curl -sI https://example.com/static/style.css
    curl -sI https://example.com/static/style.css   # second request should be HIT
  7. Set up cache invalidation. When the upstream content changes, the cache needs to know. Two patterns:

    • TTL-based — small max-age for fast invalidation, accepts brief staleness.
    • Surrogate keys + purge — mod_cache does not support tag-based purging natively; use htcacheclean to evict explicit URLs:
    sudo htcacheclean -v -r -p /var/cache/apache2/mod_cache_disk -i https://example.com/articles/123

    For full purges, htcacheclean -d runs daemon mode and prunes by size or age.

Common pitfalls

  • Caching a response with Set-Cookie will broadcast one user’s session cookie to other users — CacheIgnoreHeaders Set-Cookie (in the config above) defends against this, but verify with a curl that no cached page sets a cookie.
  • A page that varies by user (logged-in vs anonymous) must emit Cache-Control: private or use Vary correctly — caching defaults will otherwise serve the wrong content.
  • CacheLock defends the upstream but does not defend the cache from a 5xx response taking the place of a previously-cached 200 — CacheStaleOnError on lets you serve the stale copy when the upstream errors.
  • The disk cache grows indefinitely without htcacheclean running periodically — wire it into a cron or systemd timer.
  • mod_cache does not cache responses to authenticated requests in QuickHandler off mode if the auth check populated the response — for those, use cookie-aware front-of-page caching at the CDN level, not Apache.

Stack Harbor configures mod_cache for the workloads where it pays — high-traffic content sites with mostly-anonymous reads, static-heavy assets, and well-behaved upstream Cache-Control. For sites where the upstream is logged-in-heavy or session-stateful, edge-layer caching (CDN with surrogate keys) is the better tool. The pattern selection is part of the Managed Operations onboarding.