PatrickMD.net

Thoughts on Medicine and Software

PatrickMD.net Stethoscope and Textbook

How To Compress HTTP Responses with mod_php

July 14th, 2008 by Patrick

High Performance Web Sites Book Cover

For many years, I have been a fan of using compression for HTTP responses. Netscape (and I believe Internet Explorer) have supported the “Content-Encoding: gzip” header for over ten years. In the old days there was some concern over the CPU demand of streaming compression, but modern CPUs are so fast that this is no longer a major issue. Compression of HTTP responses is now a standard performance boost for major websites.

However, compression can be tricky to set up. For one thing, you don’t want to just compress every HTTP response. Graphic files, particularly JPEGs, are already compressed and show no benefit from response compression. Second, you must be careful when compressing the output of dynamically generated pages, because if the script sends its own Content-Length header this will be much longer than the now-compressed response stream. This blog entry has a good discussion of the user experience in this case (stalled download) and what to do about it.

If you are running your own Apache 2 server, you can set up mod_deflate, the standard compression module. (mod_gzip is an earlier module which was developed for Apache 1.3 and is now no longer in use.) The mod_deflate tutorial here does a good job of explaining the configuration. This won’t work if, like me, you are using a webhost and can only configure through .htaccess files.

If mod_deflate is not accessible, you can configure PHP to do the compression for you. If your PHP scripts are launched as CGIs, the “zlib” php.ini settings enable compression for all PHP requests:

zlib.output_compression=on

If you are using an Apache server with mod_php, add the following to .htaccess:

php_flag zlib.output_compression on

You can tweak the compression performance by setting the compression level. It is a number between 1 (best speed) and 9 (best compression). Level 0 is no compression at all. If the compression level is not set, defaults to level 6.

You can also set the size of the output buffer size used by PHP as it compresses the stream by passing a number to “zlib.output_compression”. If not specified, the default buffer size is 4096 bytes.

The following configuration sets compression to minimum size and provides for a 32K buffer:

php_value zlib.output_compression 32768
php_value zlib.output_compression_level 9

Tags:   · · · · · No Comments

Leave A Comment

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form above.