Quick and Easy GZIP Compression With Apache

If you’ve ever wanted or needed to enable GZIP compression for a site on your Apache server but have been confused about what to put where then this is the post for you.

This isn’t going to be very in depth, I’m just going to give you some copypasta that you can stick right in your .htaccess or vhost file ( preferably the latter, if you have the access and no-how ).

If you’re looking for a better explanation of how this type of compression works and why we do it check out this awesome article: How To Optimize Your Site With Gzip Compression. There isn’t any real byline on it, but judging from a link on the page I believe it’s the same guy who made this cool online calculator which also seems nifty.

So on to the actual content. In that article, and most others that you’ll see around the net, you’re going to do something like this to enable compression:

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

That’s cool and it works but what if you don’t know exactly what you want to be compressed by MIME type? What if you just can’t seem to get a certain filetype to compress? What if you’re just lazy like me?

The above example works by specifying exactly what you want to be compressed, leaving the rest uncompressed ( or exclusive inclusion ). The example below works by specifying exactly what you want to be served uncompressed, leaving the rest compressed ( inclusive exclusion ).

Without further ado:

SetOutputFilter DEFLATE
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png|mov|mp3|mp4|flv|swf|mpg|avi|pdf)$ \
no-gzip dont-vary
SetEnvIfNoCase Request_URI \
\.(?:exe|t?gz|zip|bz2|sit|rar)$ \
no-gzip dont-vary

You can stick this block in your .htaccess file, or in your vhost file between the VirtualHost directives but no inside of a Directory directive.

Using this style makes it easy to standardize across all of your sites, if you’d like you can even put it right in httpd.conf to do system wide compression. As long as you’re specifying everything that you wouldn’t ever want compressed it’s going to have the same functionality across all of your sites.

That’s it, all there is to it. You can literally copy paste this into your .htaccess, vhost, or httpd.conf file and have it working in seconds for any site you maintain ( remember to do service httpd reload or service apache2 reload if you’re using a vhost .conf or your global httpd.conf ).

Hopefully you find this helpful. I plan to do a better writeup on web compression in general in the near future.