How to Circumvent Your Cheap Webhost’s Restrictions: gzipping Without mod_deflate

An important rule for website optimization is to Gzip everything you send over the wire. The practice of compressing web pages, CSS and JavaScript is supported by most modern browsers. This has two advantages: Smaller files will download faster and less bandwidth will be used on the server.

On most servers, modules exist that can gzip your pages fully transparent. On Apache, the mod_deflate module takes care of this. But what do you do if your server does not have that module installed and you can’t add it? You get creative.

The trick I found on my Lunarpages hosted sites, is to pipe all files through PHP, which has a gzip library (called zlib). It’s not too difficult to get this working, but you do need to know a few things about PHP and mod_rewrite.

Check Zlib support in PHP

First things first, you’ll need to make sure that your PHP installation supports the Zlib library. You can do this by creating a small PHP file, as described in this post.

Create the PHP compress script

The idea is to pipe all files through this script. The file to compress will be passed as a parameter. Lets say you want to compress the file “js/myscript.js”, the URL to use would be: http://yoursite/gzip.php?file=js/myscript.js

Create the following gzip.php script on your server:

One thing to note, is that we have to set the “Content-Type” of the generated file. This will make sure that the browser correctly identifies the file. In this case we create a Javascript file. If you want to gzip more types, you’ll need to add some additional logic. For instance, you could check the file extension and generate a different Content-Type based on that.

Piping the requests to the PHP file

To make everything work, we now need to redirect all requests for JS files to our PHP file. Luckily, there is an easy way to do this, it’s called mod_rewrite and this module is almost always enabled on Apache installs. It can be configured by creating a .htaccess file and putting it in the root of your site:

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^/js/(.*js)$ http://yoursite/gzip.php?file=js/$1

And that’s really all there is to it. For my cable picker application, this resulted in a decrease from 3MB to only 800KB, about 30%.

If you have any other tips to circumvent weird restrictions by web hosters, feel free to share them in the comments.

Image credit.