Monday 7 July 2014

Enable gzip compression in apache

When a user types your website url in browser and hits enter, browser sends request to server. Server responds to that request in the form of reply by giving back the requested document. That document can be of any size, typically if we take javascript files, it can be between 100 to 200 KB. Is there is any way to reduce this size so that the downloading can be faster ? Answer is "yes", that's what gzip compression does. It compresses the document size to almost 70% of the original. The major benefit of gzip compression is that it reduces bandwith by reducing the size of the response from the server.

How gzip compression works ?

Below is the simple diagram that will show you how actually the whole process takes up.

Request and response without gzip compression


Request and response with gzip compression



What's next ?

Before moving to further step, we have to know that we can't control user browser. I mean to say browser may or may not support gzip encoding. However now a days all modern browser does but may be possible that it's still not supported in older browsers.

Enable it by .htaccess file

#Compress only few type
AddOutputFilterByType     DEFLATE     text/html    text/plain    text/xml    text/css


#Compress every thing except images
<Location />

# Insert filter
SetOutputFilter DEFLATE

# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html

# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip

# MSIE masquerades as Netscape, but it is fine
# BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
# the above regex won't work. You can use the following
# workaround to get the desired effect:
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# Don't compress images
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</Location>

2 comments:

  1. Nice post, very useful. I wanted to ask, how can we compress images?

    ReplyDelete
  2. Images ( like png or jpg ) uses compression internally. You can't see much size difference upon
    deflating images, in fact it may increase it'ssize

    ReplyDelete