How To Compress Traffic
This article is devoted to traffic compression. Here I will tell how to proceed speed-up uploading CSS and JS files by compressing data on a server and passing the compressed copy yo a browser.
Solutions
Automated compression by server
Insert the following code to .htaccess file:
<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_item_include file \.js$
mod_gzip_item_include file \.css$
</IfModule>
Create compressed copy of every JS/CSS file manually and send the compressed files instead of uncompressed files
You should archive these files manually and upload them to your server. This is manual work but – good news – number of files shouldn’t be too large. An advantage is that your server won’t be overloaded.
Send *.js files to *.js.gz and upload them to the same folder where original JS file is located on your server.
Add the following code to .htaccess (site root) after RewriteEngine on
:
RewriteRule ^(.*\.js\.gz)$ – [L]
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ $1.gz
Check if the work was correctly done. Load the page in a web-browser and view the request headers:
- Response Headers
- Date Wed, 19 Mar 2008 12:32:09 GMT
- Server Apache
- Cache-Control max-age=1209600
- Expires Wed, 02 Apr 2008 12:32:09 GMT
- Last-Modified Wed, 19 Mar 2008 12:31:38 GMT
- Etag “bdcf97-87d-47e107aa”
- Accept-Ranges bytes
- Content-Length 2173
- Connection close
- Content-Type application/x-gzip
- Content-Encoding gzip
Size of the received file should be less than the original one…
How it works : mod_rewrite decides which file is to be sent to a client (compressed or not). If there is a compressed copy near the original javascript.js file, and request contains info that client supports gzip-encoding, then client receives the compressed copy. If gzip-encoding isn’t supported or there is no compressed file, client gets original file.
As a result, server loading is decreased. You can do the same thing for CSS.
Good luck!