Serving Precompressed Static Content with Apache

11 Jun 2009

Using mod_negiotiation

It's pretty simple but has a big gotcha

First, edit your mine.conf file, and uncomment or add:

AddEncoding x-compress .Z
AddEncoding x-gzip .gz .tgz

and if you use Indexes comment out:

#AddType application/x-compress .Z
#AddType application/x-gzip .gz .tgz

then add Options MultiViews to any Directory that has compressible content.

Now compress your content. Hack the following as needed:

for file in *.js; do
    echo "gzipping ${file}"
    gzip -9 -c $file > ${file}.gz;

Ok now you are all set, except for one thing

You have to get rid of the suffix on your URLs. For example, if you have:

<link src ="foo.css">
You have to change it to:
<link src ="foo">

Grump. I don't really like that. The good news is that the old links (with the suffix) still work, but aren't compressed.


Smart guy Mark Aufflick figure it out another way using mod_rewrite.

It's a slight differently method. You are making new mine types .jsgz and .cssgz and telling apache explicitly what they are. The compressor script is slightly different. The output should be foo.jsgz not foo.js.gz

for file in *.js; do
    echo "gzipping ${file}"
    gzip -9 -c $file > ${file}gz;

Add these to your apache2.conf or http.conf. This sets up the new mime types:

AddType "text/javascript;charset=UTF-8" .jsgz
AddEncoding gzip .jsgz
AddType "text/css;charset=UTF-8" .cssgz
AddEncoding gzip .cssgz

Then add the gzip-if-client-can-do-it command:

<Directory "/YOUR/DIRECTORY/WITH/js">
RewriteEngine on
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteRule (.*)\.css$ $1\.cssgz [L]

etc.. ta-da! Now do the same thing with your CSS.