Enabling gzip, deflate compression on your website on apache via .htaccess


Compressing your website files, especially the text files, with mod_gzip or mod_deflate on Apache not only save heaps of network bandwidth, but also speed up downloading your website up to 70%.

Most web servers can compress hosted website files in gzip format before sending them for download. To enable compression, configure your web server to set the Content-Encoding header to gzip format for all textual resources.

Almost all modern browsers support data compression for HTML, CSS, and JavaScript files. This allows web servers to send data over the network in compressed form and help in reducing lot of network traffic and download time.

Apart from the gzip compression, you can also use deflate. Here’s a sample code that you can place in the .htaccess file at root of your website:

Enable file compression using mod_gzip

<IfModule mod_gzip.c>
    mod_gzip_on       Yes
    mod_gzip_dechunk  Yes
    mod_gzip_item_include file      \.(html?|txt|css|js|php|pl)$
    mod_gzip_item_include handler   ^cgi-script$
    mod_gzip_item_include mime      ^text/.*
    mod_gzip_item_include mime      ^application/x-javascript.*
    mod_gzip_item_exclude mime      ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

Enable file compression using mod_deflate

<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript

There are few caveats here. Compression needs processor usage and compressing media files is not recommended for following reasons:

  1. Usually media files are already optimized and there is not much to gain by compressing them.
  2. Media files such as mp3s, videos, images etc. are much larger in size and hence require more processor power out weighing the benefits of compressing them.

Check and Confirm Your Compression

Once you have added code in the .htaccess on your server, check it to make sure it’s actually serving up compressed files. you can verify it in several ways:

  1. Use the online gzip tool to check if your web page is compressed or not.
  2. You can install Google PageSpeed Firefox Addon and see whether your web page is compressed or not.

Hope that helps.