Begin main content

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*:

  1. 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' \;
    
  2. 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
  3. 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 | Comments (0)

XML

Blog Categories

software (39)
..cocoa (21)
  ..heads up 'tunes (5)
..ruby (6)
..lisp (3)
..perl (4)
..openacs (1)
mac (20)
embedded (2)
..microprocessor (2)
  ..avr (1)
electronics (3)
design (1)
photography (25)
..black and white (6)
..A day in Sydney (18)
..The Daily Shoot (6)
food (2)
Book Review (2)

Notifications

Icon of Envelope Request notifications

Syndication Feed

XML

Recent Comments

  1. Unregistered Visitor: An other Script
  2. Unregistered Visitor: A message in there?
  3. Unregistered Visitor: using Amazon S3
  4. Unregistered Visitor: Thank you ! Thank you ! Thank you !
  5. Unregistered Visitor: Umbrello on leopard
  6. Unregistered Visitor: Script gor generate for library
  7. Unregistered Visitor: Similar but different
  8. Unregistered Visitor: Thanks for fixing my problem!
  9. Unregistered Visitor: Pop up once the category is been defined
  10. Unregistered Visitor: smal amendment