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 (usingmod_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-storeorCache-Control: privateis not cached. - A response with
Set-Cookieis not cached unlessCacheStoreNoStore Onand similar overrides. - A response with
Vary: Cookieis keyed by the request’sCookie:header — typically uncacheable in practice. - A response with a non-2xx status and no
Expires/max-ageis 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
-
Enable the modules.
sudo a2enmod cache cache_disk expires headers sudo apache2ctl configtest sudo systemctl reload apache2 -
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 offruns the cache later in the request lifecycle — slower but allowsmod_rewriteandmod_authrules to fire before the cache hit. The “on” variant is faster but skips authentication, which can serve restricted content publicly.CacheLock onprevents 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. -
Enable caching per-vhost or per-location. The
CacheEnabledirective 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> -
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_expiresadds 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" -
Enable and reload.
sudo a2enconf mod_cache sudo apache2ctl configtest sudo systemctl reload apache2 -
Verify hits and misses. With
CacheDetailHeader on, responses include anX-Cache-Detailheader 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 -
Set up cache invalidation. When the upstream content changes, the cache needs to know. Two patterns:
- TTL-based — small
max-agefor fast invalidation, accepts brief staleness. - Surrogate keys + purge —
mod_cachedoes not support tag-based purging natively; usehtcachecleanto evict explicit URLs:
sudo htcacheclean -v -r -p /var/cache/apache2/mod_cache_disk -i https://example.com/articles/123For full purges,
htcacheclean -druns daemon mode and prunes by size or age. - TTL-based — small
Common pitfalls
- Caching a response with
Set-Cookiewill 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: privateor useVarycorrectly — caching defaults will otherwise serve the wrong content. CacheLockdefends the upstream but does not defend the cache from a 5xx response taking the place of a previously-cached 200 —CacheStaleOnError onlets you serve the stale copy when the upstream errors.- The disk cache grows indefinitely without
htcachecleanrunning periodically — wire it into a cron or systemd timer. mod_cachedoes not cache responses to authenticated requests inQuickHandler offmode 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.