Apache 2 compression the easy way

Gzip (or on Apache 2, Deflate) compression is a godsend. Rather than try to deal with changing content headers in code, with a few simple httpd.conf settings you can get nearly all the advantages instantly. Now possibly ancient browsers can choke on this, but it will work for everybody who has a browser built since the millenium – to accommodate the old folks we have a BrowserMatch condition. Add some simple expiration rules and you’ve probably sped up your serving by at least 70%.

Make sure you’ve enabled mod_deflate via LoadModule, then add this to the main section, or your virtual host(s).

httpd.conf

...
<IfModule mod_deflate.c>
 
# Netscape 4.X has some problems
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
 
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/css
 
# turn on the module for this directory
ExpiresActive on
 
# cache common graphics for 3 days
ExpiresByType image/jpg 		"access plus 3 days"
ExpiresByType image/gif 		"access plus 3 days"
ExpiresByType image/jpeg 		"access plus 3 days"
ExpiresByType image/png 		"access plus 3 days"
 
# cache CSS and JS for 24 hours
ExpiresByType text/css 			"access plus 24 hours"
ExpiresByType application/x-javascript 	"access plus 24 hours"
</IfModule>

Some good links with more info here and here.

Leave a comment

Your email address will not be published. Required fields are marked *