A comprehensive guide to configuring caching and compression in Apache2 for optimal performance.
Before configuring caching on Apache2, ensure you have:
<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:
<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>
<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:
# Apache configuration will appear here