Skip to main content

Implementing Caching Strategies

1. Enabling Cache Modules

Module Description Enabled by Default Configuration Directive
mod_cache Core caching module that provides the framework for caching content. No LoadModule cache_module modules/mod_cache.so
mod_cache_disk Provides disk-based caching for content. No LoadModule cache_disk_module modules/mod_cache_disk.so
mod_cache_dbm Provides DBM-based caching for content. No LoadModule cache_dbm_module modules/mod_cache_dbm.so
mod_expires Controls the setting of Expires and Cache-Control headers. No LoadModule expires_module modules/mod_expires.so
mod_headers Allows modification of headers sent to the client. No LoadModule headers_module modules/mod_headers.so

Example: Enabling Disk-Based Caching

# Load required modules
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule expires_module modules/mod_expires.so

# Configure cache storage
CacheRoot /var/cache/apache2/cache
CacheEnable disk /
CacheDefaultExpire 3600
CacheLastModifiedFactor 0.1
CacheMaxExpire 86400

# Set cache control headers
ExpiresActive On
ExpiresDefault "access plus 1 hour"

2. Configuring Disk-Based Cache

Directive Description Values Notes
CacheEnable Enables caching for a specific URL or directory disk:/path/to/cache Must be used with CacheRoot to define cache location
CacheRoot Defines the root directory for disk-based caching Path to directory Must be an absolute path
CacheDefaultExpire Sets default expiration time for cached content Time in seconds or format like 1 hour Applies to all cached content if not overridden
CacheLastModifiedFactor Adjusts cache expiration based on last modified time Float between 0 and 1 Default is 0.1
CacheMaxExpire Sets maximum expiration time for cached content Time in seconds or format like 1 day Prevents caching beyond this limit

Example: Basic Disk Cache Configuration

<IfModule mod_cache.c>
    CacheEnable disk /cached-content
    CacheRoot /var/cache/apache
    CacheDefaultExpire 3600
    CacheMaxExpire 86400
</IfModule>

Example: Cache Configuration with Last Modified Factor

<IfModule mod_cache.c>
    CacheEnable disk /cached-content
    CacheRoot /var/cache/apache
    CacheDefaultExpire 3600
    CacheLastModifiedFactor 0.5
    CacheMaxExpire 86400
</IfModule>
Note: Ensure that the cache directory has proper read/write permissions for the Apache user.
Warning: Disk-based caching can consume significant storage space. Monitor cache size regularly.

3. Enabling Cache for Paths

Directive Values Description
CacheEnable cache Enables caching for specified paths or URLs
CacheRoot /var/cache/httpd Specifies the root directory where cached content is stored
CacheDefaultExpire 3600 Sets default cache expiration time in seconds (1 hour)

Example: Enabling Cache for Specific Paths

<IfModule mod_cache.c>
    CacheEnable cache "/images/"
    CacheEnable cache "/static/css/"
    CacheRoot /var/cache/httpd
    CacheDefaultExpire 3600
</IfModule>
Note: Ensure that the CacheRoot directory has proper read/write permissions for the Apache user.

4. Disabling Cache for Paths

Path Directive Description
/api/* CacheDisable Disables caching for all requests under the /api/ path.
/static/css/* CacheDisable Prevents caching of CSS files in the static directory.

Example: Disabling Cache for API Endpoints

<LocationMatch "/api/.*">
    CacheDisable On
</LocationMatch>

Example: Disabling Cache for Static Assets

<LocationMatch "/static/css/.*">
    CacheDisable On
</LocationMatch>

5. Setting Cache Expiration

Directive Values Description
ExpiresActive on | off Enables or disables the Expires module. Default is off.
ExpiresDefault access | modification | time Sets default expiration time relative to access or modification time.
ExpiresByType MIME type and time Assigns expiration times to specific MIME types.
ExpiresByLocation URL pattern and time Applies expiration based on URL location patterns.

Example: Setting Cache Expiration for Static Assets

<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresDefault "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
</IfModule>
Note: The ExpiresByType directive uses MIME types to define cache behavior. Ensure that the correct MIME types are set for your server configuration.

Example: Using ExpiresByLocation for Specific Paths

<IfModule mod_expires.c>
  <Location "/static">
    ExpiresActive on
    ExpiresDefault "access plus 1 day"
  </Location>
</IfModule>
Warning: Setting very long cache times (e.g., years) can cause issues when content is updated. Always test cache behavior in staging environments.

6. Configuring Cache Size Limits

Directive Values Description
CacheRoot /var/cache/httpd Root directory for cache storage
CacheSize 5000 Maximum number of cached entries (default 5000)
CacheGcClean On Enable garbage collection to clean expired entries
CacheMaxExpire 86400 Maximum cache expiration time in seconds (1 day)

Example: Setting Cache Size Limits

<IfModule mod_cache.c>
    CacheRoot /var/cache/httpd
    CacheSize 10000
    CacheGcClean On
    CacheMaxExpire 3600
</IfModule>
Note: Ensure sufficient disk space is allocated for the cache directory to avoid performance degradation.

7. Using Shared Object Cache

Directive Description Values Notes
CacheEnable Enables caching for a specific URL or directory disk:/path/to/cache, mem:/path/to/memcache Must be used with CacheRoot or CacheDir
CacheRoot Defines the root directory for cache storage /var/cache/httpd Must be set to a valid directory path
CacheDir Defines the directory structure for cache storage /var/cache/httpd Can be used to organize cache by URL or content type
CacheDefaultExpire Sets default expiration time for cached content 3600 (seconds) Default is 3600 seconds (1 hour)
CacheMaxExpire Sets maximum expiration time for cached content 86400 (seconds) Maximum cache duration is 24 hours

Example: Enabling Shared Object Cache

<IfModule mod_cache.c>
    CacheEnable disk /
    CacheRoot /var/cache/httpd
    CacheDir /var/cache/httpd
    CacheDefaultExpire 3600
    CacheMaxExpire 86400
</IfModule>
Note: Ensure that the cache directory has proper permissions for Apache to read and write files.
Warning: Caching may cause issues with dynamic content. Ensure that cache policies are correctly configured to avoid serving stale content.

8. Configuring Cache Lock

Directive Description Default Notes
CacheLock Enables or disables cache locking for shared memory cache implementations Off Used to prevent race conditions in concurrent access to cache entries
CacheLockPath Specifies the directory where cache lock files are stored /tmp Must be a directory with write permissions for the web server process
CacheLockTimeout Defines the maximum time (in seconds) to wait for a cache lock before timing out 5 Set to 0 for no timeout (not recommended in high-concurrency environments)

Example: Enabling Cache Locking

<IfModule mod_cache.c>
    CacheLock On
    CacheLockPath /var/cache/httpd
    CacheLockTimeout 10
</IfModule>
Note: Cache locking is essential in environments where multiple requests may attempt to access or update the same cached resource simultaneously. Misconfiguration can lead to performance degradation or deadlocks.

9. Setting Cache Headers

Header Values Description
Cache-Control max-age=3600, no-cache, no-store Controls caching behavior for both public and private caches
Expires Wed, 21 Oct 2026 07:28:00 GMT Defines an absolute date/time after which the response is considered stale
ETag "33a64df54f" Unique identifier for a specific version of a resource
Last-Modified Wed, 21 Oct 2026 07:28:00 GMT Timestamp of the last modification of the resource

Example: Setting Cache-Control Header

<FilesMatch "\.(css|js|png|jpg)$">
  Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

Example: Setting Expires Header

<Location "/static/">
  ExpiresActive On
  ExpiresDefault "access plus 1 year"
</Location>

10. Using ETags for Validation

Directive Description Default Notes
FileETag Controls which file attributes are used to generate ETags None Can include Inode, MTime, Size
ETag Enables or disables ETag generation On Can be set to Off to disable ETags entirely

Example: Configuring ETags

<FilesMatch "\.(css|js)$">
    FileETag MTime Size
</FilesMatch>

<Location "/static/">
    ETag On
</Location>
Note: ETags are used in conjunction with If-None-Match requests to validate if a cached resource is still valid.
Warning: Using Inode in FileETag can cause issues if files are moved or copied, as inode numbers may change.
ETag Type Description Use Case
MTime Based on file modification time Good for static content that doesn't change often
Size Based on file size Simple and fast, but less reliable for content changes
Inode Based on file system inode number Can be problematic in shared environments or when files are copied

11. Managing Cache Invalidation

Directive Description Values Notes
CacheEnable Enables caching for a specific URL or directory disk:/path/to/cache Must be used with CacheRoot
CacheDisable Disables caching for a specific URL or directory /path/to/disable Overrides CacheEnable
CacheDefaultExpire Sets default expiration time for cached content 3600 (seconds) Defaults to 3600 seconds (1 hour)
CacheLastModifiedFactor Adjusts cache expiration based on Last-Modified header 0.1 to 1.0 Value between 0 and 1; affects how much time is added to expiration
CacheStoreNoStore Prevents storing content with No-store directive On, Off Defaults to Off

Example: Enabling Caching for Static Assets

<IfModule mod_cache.c>
    CacheEnable disk /static/
    CacheDefaultExpire 86400
    CacheLastModifiedFactor 0.5
</IfModule>

Example: Disabling Caching for Dynamic Content

<IfModule mod_cache.c>
    CacheDisable /dynamic/
    CacheDisable /api/
</IfModule>
Note: Cache invalidation strategies depend on proper handling of ETags and Last-Modified headers. Ensure that your application updates these headers correctly when content changes.
Warning: Misconfigured cache invalidation can lead to serving stale content. Always test cache behavior in a staging environment before deploying to production.

12. Monitoring Cache Performance

Example: Enabling Cache Monitoring

<IfModule mod_cache.c>
  CacheEnable disk /
  CacheRoot /var/cache/apache2
</IfModule>

<IfModule mod_cache_disk.c>
  CacheDirLevels 2
  CacheDirLength 1
</IfModule>
Directive Description Default Notes
CacheEnable Enables caching for specified type and path None Must be set to enable caching
CacheRoot Directory where cached content is stored /var/cache/apache2 Must be writable by Apache user
CacheDirLevels Number of subdirectories to create 1 Higher levels reduce file system load
CacheDirLength Length of directory names 1 Used with CacheDirLevels to organize cache
Note: Cache monitoring requires mod_cache and mod_cache_disk to be loaded.

Example: Cache Statistics Logging

<IfModule mod_cache.c>
  CacheEnable disk /
  CacheRoot /var/cache/apache2
  CacheLogLevel info
</IfModule>

Cache Performance Metrics

  • Hit Ratio: Percentage of requests served from cache
  • Miss Ratio: Percentage of requests that bypassed cache
  • Average Cache Time: Time spent in cache before expiration
  • Cache Size: Total size of cached content

Steps to Monitor Cache Performance

  1. Enable cache logging with CacheLogLevel
  2. Check Apache logs for cache statistics
  3. Analyze hit/miss ratios using log parsing tools
  4. Adjust cache configuration based on performance data

Was this article helpful?