In this post I will demonstrate how to compress text content in your web applications or websites, so that the traffic size is smaller and, consequently, the loading time of your application is smaller.

To do this, we will use the Apache Web server configuration file, .htaccess. Remember that files such as videos, music and other binary files are probably already compressed and as they are generally much larger in size than text files, it would require a lot of server processing to compress them again, and the gain from compression would be minimal.

For this reason, it is recommended to activate compression only in text files, and especially in the “Big 3” (HTML, CSS and Javascript).

Enabling compression with DEFLATE

This is the easiest compression to configure on the server and is already enabled by default. It uses less server processing than GZip, but does not compress as much as it does.

<IfModule mod_deflate.c>

    # Compactar por tipo - html, text, css, xml
    AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml

    # Compactar por tipo - javascript
    AddOutputFilterByType DEFLATE application/x-javascript application/javascript text/javascript text/x-js text/x-javascript

    # Compactar por extensão
    AddOutputFilter DEFLATE js css htm html xml ttf eot

</IfModule>

Enabling compression with GZip

GZip is gaining a lot of space nowadays on the Web due to its great data compression power, drastically reducing page loading times, especially when we talk about mobile internet (3G) in Brazil, which is still very slow and precarious in many places. As it presents a high level of compression, it requires more processing than the DEFLATE compression method.

<IfModule mod_gzip.c>
    mod_gzip_on       Yes
    mod_gzip_dechunk  Yes
    mod_gzip_item_include file      \.(html?|txt|css|js|php|pl|ttf|eot)$
    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.*
</IfModule>