GZip – using mod_gzip, mod_deflate and htaccess

Apache server supports server level GZip compression with the help of module mod_gzip and mod_deflate. You can use this module and enable GZip compression for your website using htaccess file. First you have to check whether your hosting provider has enabled mod_gzip or mod_deflate module or not? To check this, you can use php_info() function of PHP which prints all the information about server and modules.

You can enable compression for text and html by adding following lines in your htaccess file.

# compress all text and html:
AddOutputFilterByType DEFLATE text/html text/plain text/xml

# Or, compress certain file types by extension:

SetOutputFilter DEFLATE

You can compress all type of content (image, css, js etc) using mod_deflate. Copy following code in htaccess to do this.

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

Also, you can add following code in your htaccess file and enable compression using mod_gzip.

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.*

This technique only works if mod_gzip or mod_deflate modules are loaded in Apache. In our case, these modules were not there and our hosting provider refused to load it as we were using a shared hosting. So following can be another way of enabling compression.

Leave a Reply

Your email address will not be published. Required fields are marked *