Sunday, October 4, 2009

Using gzip encoding in Apache without mod_gzip or mod_deflate

To reduce bandwidth and speed you can install mod_gzip or mod_deflate with your Apache configuration. Unfortunately there are hosting providers who don’t have either of these modules installed.

With a little bash scripting and some modifications of your .htaccess you can accomplish almost the same thing. If you run a dynamic site, with PHP for example, you can’t compress the HTML file itself but you can compress Javascript and Style Sheets files.

First we need to download our website to our local machine, use your favorite FTP client and download it to a directory of your choice, in this article I’ll be downloading it to /d1/websites/ in the directory blog


If you happen to use the FileZilla FTP client you don’t have to download everything, you can setup a filter which will allow you to only download .js and .css files.

Next you go to the parent directory where you downloaded your website.

# cd /d1/websites

Open your favorite editor and create a file called compress.sh and enter the following in the file:

1
2
3
4
5
6
7
#!/bin/bash
for file in `find . -name *js -type f`; do
        gzip -c $file >$file.gz
done
for file in `find . -name *css -type f`; do
        gzip -c $file >$file.gz
done

Next you need to make sure this file is executable

# chmod +x compress.sh

Now run the file
# ./compress.sh

We have to make some changes in the .htaccess file, it should be located in the directory blog, if it’s not create it. Open this file and add the following lines at the beginning. If there already is a mod_rewrite section, you can copy the lines 5 through 18 in that section.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

RewriteEngine On
RewriteBase /
 
# Add some gzip to the bunch
RewriteCond %{REQUEST_FILENAME} ^.+\.(js|css)$ [NC]
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.+)$ $1.gz [L,QSA,NC,NS]
 

        ForceType text/javascript
        Header set Content-Encoding "gzip"


        ForceType text/css
        Header set Content-Encoding "gzip"


Now upload the blog directory back to your website and you are all set. This should work with Apache 1.3 as well as Apache 2.x.

Some notes for WordPress users. When you update a plugin through the admin interface the gzipped file will no longer be there, this won’t be problem the uncompressed file will be served, but when you update the core you have to do this again.

The old gzipped file will still be there and will be used and you can imagine that could lead to all sort of problems.

No comments:

Post a Comment