Archive for July, 2007

How to use Apache to compress (gzip) HTML, CSS and Javascript files

Tuesday, July 17th, 2007

In an earlier post we showed you how to use PHP to compress html files and save valuable bandwidth. Now we will choose a setup where apache will compress the files. This is a more efficient setup for your serverconfiguration.

Installing mod-deflate

When Apache 2 is installed, mod_deflate is automatically installed, but not always enabled. To enable mod_deflate on a debian or ubuntu distribution, we can do:
a2enmod deflate
On another system you have to edit Apache2’s configuration file manually. First locate mod_deflate.so then edit the config file. Add this to the LoadModule section:
LoadModule deflate_module /PATH_TO/mod_deflate.soThen restart Apache
apache2ctl restart

Enable the SetOutputFilter DEFLATE filter

Compression for APACHE 2 is implemented by the DEFLATE filter. To enable compression for documents simply put this filter in the appropriate Directory directives:

SetOutputFilter DEFLATE

But we don’t want to compress picture-files

But we do not want to compress everything! It doesn’t make any sense to compress files like gif, jpg or pdf’s. So we have to make an execption:

// Don't compress picture files
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ \ no-gzip dont-vary
// Don't compress compressed files
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ \no-gzip dont-vary
// Don't compress pdf's
SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-vary

Conclusion

Enabling compression is amazingly easy. Simply enable it in your apache directives. To sum it all up:

SetOutputFilter DEFLATE
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ \ no-gzip dont-vary
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ \no-gzip dont-vary
SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-var

If you can’t edit your directives, you can alternatively use the .htaccess files in your webroot directory.
That’s all folks!

Your are browsing
the Archives of My Beloved PHP for July 2007.
Categories
Archives
Links