Speed up your web page – Serve Gzipped content

Today most of the browsers accept compressed content. See this. The compression on a Linux box can be achieved using GNU Zip or GZip. Here is a simple .htaccess trick to serve gzipped content to browsers.

<FilesMatch "\.(js|css)$">
RewriteEngine on
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ %{REQUEST_URI}.gz [L,QSA]
</FilesMatch>
<FilesMatch "\.(js|css)\?.*$">
RewriteEngine on
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^([^?]*)\?(.*)$ $1.gz?$2 [L]
</FilesMatch>
<FilesMatch "\.js\.gz(\?.*)?$">
AddEncoding x-gzip .gz
AddType text/javascript .gz
</FilesMatch>
<FilesMatch "\.css\.gz(\?.*)?$">
AddEncoding x-gzip .gz
AddType text/css .gz
</FilesMatch>

What this script does is very simple. It simply rewrites the request for browsers that accept compressed files from .css or .js to .css.gz or .js.gz ONLY if corresponding .gz files are available on file system. Then serves .gz files with a proper encoding. To use this on your server, you must have
a) Linux – Elementary
b) Apache – Again, elementary
c) gzip – If you are on Linux, you have it
d) mod_rewrite – mod_rewrite enabled.
e) .htaccess – you must have ability to create and use .htaccess
Now .js files can be zipped with following shell script snippet

for i in `find ./  -name  "*.js"`
do
gzip -9 -c -f $i > $i.gz
done

The shell script snippet above can be reduced to one line and can also compress html/css/js files. How? Find out and tell me. 😉