Categorized | Mod_Deflate

Tags : , ,

mod_deflate alternative way for css and javascript through mod_rewrite rules

Posted on 20 January 2010

This method is probably the best method to overcome the mod_deflate issue and we are only concerned about javascript and css files for now. What we need to do is gzip all our javascript & css files. (Note: PHP has an easy method to compress php files on the fly).

You have to have shell access to your server/website.  Run follow command will find each and every javascript file and css file and create a gzip copy.

cd /folder_to_your_website_root_folder
find . -regex ".*\(css\|js\)$" -exec bash -c 'echo Compressing "{}" && gzip -c --best "{}" > "{}.gz"' \;

The line above searches the current directory and any subdirectories for files with extensions .js or .css, then prints out that it is being compressed, then compresses with the highest compression in that directory leaving the original file as is.

Now, we need to tell our browser to access the gzip version *IF* it supports gzip encoding.
To do this, we use the following in our .htaccess file ( create that file if not exists in your website root folder)

<files *.js.gz>
	AddType "text/javascript" .gz
	AddEncoding gzip .gz
</files>
<files *.css.gz>
	AddType "text/css" .gz
	AddEncoding gzip .gz
</files>

RewriteEngine on
#Check to see if browser can accept gzip files.
ReWriteCond %{HTTP:accept-encoding} gzip
RewriteCond %{HTTP_USER_AGENT} !Safari

#make sure there's no trailing .gz on the url
ReWriteCond %{REQUEST_FILENAME} !^.+\.gz$

#check to see if a .gz version of the file exists.
RewriteCond %{REQUEST_FILENAME}.gz -f

#All conditions met so add .gz to URL filename (invisibly)
RewriteRule ^(.+) $1.gz [QSA,L]

The advantage of above method is that our server doesn’t have to gzip / compress the javascript and css each time it is called. This eases the load up on the server as we already do the compression one time and then just call the compressed version from then after. (the method is very useful if you are running a VPS with very low memory available)

This post was written by:

- who has written 11 posts on The Developer.

PHP / MYSQL developer

Contact the author

Leave a Reply

You must be logged in to post a comment.