How to enable gzip compression in Apache 2.x

Written by
Date: 2011-08-24 07:30:00 00:00


If you check your website stats, you will see that most of your visitors are using modern web browsers, those browsers now support gzip (compressed) content. What does that mean?.

Of course you know about zipping a file or group of files to make them use less space, maybe you zipped files to send them via email. Well, today web servers can also compress the content before sending it to your readers, speeding up your site, and lowering the bandwidth requirements of your server.

When a visitor's browser ask for a page of your site, it will let your server know if it can handle compressed content, and if that is the case, it is desirable that your server can send a compressed version of your page.

How to enable web page compression in Apache

First lets be sure your server supports compression, to do that it needs to have the mod_deflate module:

cat httpd.conf | grep deflate

You should see this:

LoadModule deflate_module modules/mod_deflate.so

If it is commented, comment it out.

Now edit the file httpd.conf or Apache2.conf depending on your distribution.

And add these lines, at the end of the file:

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE

# You can't compress what is already compressed

SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary

# Make proxies work as they should.
<IfModule mod_headers.c>
Header append Vary User-Agent
</IfModule>

</IfModule> 

The mod_deflate module sends a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent to a client that will not understand it.

Now simply restart Apache and you are done, you can check your site here