gzip responses from Apache

Since I'm talking about Apache, I figured I might as well make a note about how to enable gzip compression on files served by Apache. This isn't exactly necessary for a dev server, but it's nice to be able to open dev tools and see precisely how much of a difference gzip compression makes. Unfortunately, like most things Apache, it's more complicated than nginx.

There are plenty of pages and blog posts that talk about this, and I've mainly referred to a post on neiland.net for the specific config tweaks. Nonetheless, I'll list them here.

Make sure mod_deflate is being loaded in httpd.conf:

LoadModule deflate_module libexec/apache2/mod_deflate.so  

Create a separate file with the specifics of what should and shouldn't be gzipped. On my system, I made /etc/apache2/extra/httpd-deflate.conf, here are the contents:

#Set to gzip all output
SetOutputFilter DEFLATE

#exclude the following file types
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|iso|tar|bz2|sit|rar|png|jpg|gif|jpeg|flv|swf|mp3)$ no-gzip dont-vary

#set compression level
DeflateCompressionLevel 9

#Handle browser specific compression requirements
BrowserMatch ^Mozilla/4 gzip-only-text/html  
BrowserMatch ^Mozilla/4.0[678] no-gzip  
BrowserMatch bMSIE !no-gzip !gzip-only-text/html  
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0a  

That says compress everything except things that are already compressed based on file extensions. It also says use the highest compression setting. Since we all have fast CPUs, this should be fine and we'll end up with the smallest possible file sizes. There's some legacy browser stuff in there too which I've left in even though the chances of one of those hitting my dev server is nil. For the record, I didn't come up with that but copied it from the aforelinked neiland.net blog post.

Next tell apache about the new file by using Include at the bottom of httpd.conf:

# Deflate configuration
Include /etc/apache2/extra/httpd-deflate.conf  

Restart apache:

apachectl restart  

Verify that apache is serving gzipped responses via browser dev tools:
gzipped and uncompressed file sizes via Chrome dev tools' network tab