home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Practical mod_perlPractical mod_perlSearch this book

11.9. Response Compressing

Have you ever served a huge HTML file (e.g., a file bloated with JavaScript code) and wondered how you could send it compressed, thus dramatically cutting down the download times? After all, Java applets can be compressed into a jar and benefit from faster download times. Why can't we do the same with plain text files (HTML, JavaScript, etc.)? Plain text can often be compressed by a factor of 10.

Apache::GzipChain can help you with this task. If a client (browser) understands gzip encoding, this module compresses the output and sends it downstream. The client decompresses the data upon receiving it and renders the HTML as if it was fetching uncompressed HTML. Furthermore, this module is used as a filter, thanks to Apache::OutputChain, and can therefore compress not only static files but also dynamic content created from your handlers or scripts.

For example, to compress all HTML files on the fly, do this:

<Files *.html>
    SetHandler perl-script
    PerlHandler Apache::OutputChain Apache::GzipChain Apache::PassFile
</Files>

Browsers are supposed to declare that they can handle compressed input by setting the Accept-Encoding header. Unfortunately, many browsers cannot handle it, even if they claim that they can. Apache::GzipChain keeps a list of user agents, and also looks at the User-Agent header to check for browsers known to accept compressed output.

As an example, if you want to return compressed files that will in addition pass through the Embperl module, you would write:

<Location /test>
    SetHandler perl-script
    PerlHandler Apache::OutputChain Apache::GzipChain \
                Apache::EmbperlChain Apache::PassFile
</Location>

Watch the access_log file to see how many bytes were actually sent, and compare that with the bytes sent using a regular configuration.

Notice that the rightmost PerlHandler must be a content producer. Here we are using Apache::PassFile, but you can use any module that creates output.

Alternatively, you may want to try Apache::Compress, which is compatible with Apache::Filter and is covered in Appendix B. To compress only outgoing static files, you can look at the mod_gzip and mod_deflate modules for Apache.

The cool thing about these modules is that they don't require any modification of the code. To enable or disable them, only httpd.conf has to be tweaked.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.