Serve pre-compressed content with Apache
I wanted to serve compressed static js and css content from an Apache server. I also wanted to pre-compress the files to save time/cpu, and the particular Apache 2 instance had no mod_deflate or mod_gzip installed (dynamic content was being compressed at the application layer).
Serving pre-compressed content turned out to be incredibly easy using mod_rewrite*:
- Create a compressed copy of each .js & .css file with a .jsgz/.cssgz extension
find . -name '*.js' -or -name '*.css' -exec sh -c 'gzip -c {} > {}gz' \;
- Add the following to a relevant part of your Apache config file:
RewriteEngine on RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule (.*)\.css$ $1\.cssgz [L] AddType "text/css;charset=UTF-8" .cssgz AddEncoding gzip .cssgz RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule (.*)\.js$ $1\.jsgz [L] AddType "text/javascript;charset=UTF-8" .jsgz AddEncoding gzip .jsgz
- Test & reload your apache config
httpd -t httpd -k graceful
Voila, correctly served pre-compressed static files. Just be sure to update your compressed versions whenever you update the content.
* ``The great thing about mod_rewrite is it gives you all the configurability and flexibility of Sendmail. The downside to mod_rewrite is that it gives you all the configurability and flexibility of Sendmail.'' -- Brian Behlendorf, Apache Group
11:04 PM, 06 Dec 2007 by Mark Aufflick Permalink | Short Link







