How to Setup Caching on Apache2

A comprehensive guide to configuring caching and compression in Apache2 for optimal performance.

Prerequisites

Before configuring caching on Apache2, ensure you have:

  • Apache2 installed and running
  • Root or sudo access to the server
  • Basic understanding of HTTP caching concepts
  • Required modules enabled (mod_expires, mod_headers, mod_deflate)

mod_expires Configuration

Cache Configuration
<IfModule mod_expires.c>
    ExpiresActive On
    
    # Set default expiry
    ExpiresDefault "access plus 1 month"
    
    # Images
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    
    # CSS, JavaScript
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    
    # HTML documents
    ExpiresByType text/html "access plus 0 seconds"
</IfModule>

Key directives explained:

  • ExpiresActive: Enables the expiration module
  • ExpiresDefault: Sets default expiration time
  • ExpiresByType: Sets expiration by MIME type

Cache-Control Headers

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

<FilesMatch "\.(html|htm)$">
    Header set Cache-Control "public, no-cache"
</FilesMatch>

<FilesMatch "^api/">
    Header set Cache-Control "no-store"
    Header set Pragma "no-cache"
</FilesMatch>

Deflate Compression

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE image/svg+xml
    
    # Avoid compression for older browsers
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>

Compression settings explained:

  • AddOutputFilterByType: Enables compression for specific MIME types
  • BrowserMatch: Browser-specific compression rules

Configuration Generator

Generated Configuration
# Apache configuration will appear here

Best Practices

Recommended Practices
  • Static Assets:
    • Use long cache times (1 year) with versioned URLs
    • Add Cache-Control: public for CDN caching
    • Enable deflate compression for text-based assets
  • Dynamic Content:
    • Use shorter cache times
    • Implement cache busting for updates
    • Consider using no-cache for user-specific content
  • API Responses:
    • Use no-store for sensitive data
    • Implement ETag headers for validation
    • Consider using Vary header for different responses