Javascript Compression with Apache 2 and Debian Etch

If you’re trying to wring every last drop of performance out of a website you’re probably wanting to compress all your content before it hits the wire. While I was messing about with another project I noticed that the javascript from this blog wasn’t getting compressed.

If you just want the solution to the issue, skip to the bottom of this post, but for those interested in the finer detail, read on.

This site uses Apache 2 on Etch, and after a bit of Googling I didn’t really find a direct mention of this issue, so I though I’d slap it on here for other folks afflicted with un-compressed javascript.

First step is to enable mod_deflate in the first place, which will by default compress html, xml, css and plain text files, but due to a config issue will not get your javascript.

The command to enable mod_deflate is: ‘a2enmod deflate’. If you’re on shared hosting without this configured you’ll have to drop your support folks an email, although I’d think most shared hosting companies would be well on top of the config of mod_deflate as it saves them money!

The reason javascript is not compressed by default is that the mime-type specified in /etc/apache2/mods-available/deflate.conf for javascript is ‘application/x-javascript’.

Apache dosn’t know what extension is associated with this mime type. The mime-types used by apache are defined in /etc/apache2/mods-available/mime.conf by including /etc/mine.types.

/etc/mime.types in turn has the .js extension associated with application/javascript, not x-javascript.

To fix this up you’ve got a some options:

  • Change /etc/mine.types to be application/x-javascript, which might break other applications that include that file.
  • Change /etc/apache2-mods-available/deflate.conf to use application/javascript
  • Add the mime type ‘application/x-javascript’ to /etc/apache2/mods-available/mime.conf with the line: ‘AddType application/x-javascript .js’ which is the option I took.

After adding the line do a /etc/init.d/apache reload and you’re in business, all .js files leaving your server will be compressed if the browser reports that it accepts compressed files.

You could of course pre-compress the files and serve them using .gz extensions, or control specific compression rules using a .htaccess file, but I wanted server-wide compression without needing to specifically configure sites on the server.

Leave a Reply