
How to compress your web content using gzip compression
What is GZIP ?
Gzip stands for GNU zip Compression algorithm which is actually a combination of LZ77 and Huffman Codes.
Most of the modern web browsers including mobile web browsers support gzip encoded compressed files. The web servers like Apache or IIS can be configured to serve files and any other public objects as gzipped content. Whereas Nginx has built in http-compression.
Why is it useful ?
Gzip can compress size of your webpages by up to 70%. In that sense, your web content simply becomes faster to access by web browsers. Faster access means more people are likely to read that content in lesser amount of time.
This remarkable result in bandwidth saving helps boosting up the site, plus adds to its SEO.
Disadvantages :
Compression requires more CPU usage in general, but the results achieved are more more advantageous than that of CPU exhaustion.
Here is a video from Google Webmasters explaining what this compression is :
How to achieve compression ? – Configuration of your web server :
If you use Apache as your web server, you have 2 options to use for compression. Because Apache has 2 methods :
- mod_deflate ( standard and recommended )
- mod_gzip ( predecessor of mod_deflate )
To set up compression on your web site, simply add the following lines in your .htaccess file.
AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript
more advanced code : if you want to add specific instructions for filetypes or browsers, use the following code also.
SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|ico|png)$ \ no-gzip dont-vary SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ \no-gzip dont-vary SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-vary BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Explanation :
- Set deflate environment
- Do not compress images
- Ignore already compressed files
- Leave PDF files as they are.
- For older browsers ( line 5 -8)
You can also set compress using php by applying the usage of ZLIB compression encoding . All you have to do is, add the following lines of code in your php file :
<?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], "˜gzip')) ob_start("ob_gzhandler"); else ob_start(); ?>
After you are done doing your job, its time to test and analyze the headers. Use your browser’s developer console to view and analyze headers. For Chrome use Ctrl+Shift+i, for Mozilla use Ctrl+Shift+Q to see network requests and information.
Online tools to check and verify compression of your web page :