What is compression
If you want to send a large file by email, you normally zip it. Using a tool like Winzip, you make the file much smaller. The receiver uses a similar tool to unzip the file and open the original document. Great, you've just sent a smaller file to someone else, without losing any data.
Compressions for your website is very similar: your webserver uses a compression algorithm to reduce the file size of your site. Your browser understands that mechanism, de-compresses it, and shows you the website. The result is smaller files and a faster experience for your visitor.
Using compression can reduce the page size by up to 70%, and it's easy to set up. A quick win to improve your page speed.
What to compress?
Because it compresses text, it should be used on the following file types:
- CSS files
Don't try to compress images: they'll only get larger because formats like PNG, JPEG, and GIF already include compression. Compress text-based files only
Gzip and Brotli
Two common compression algorithms are Gzip and Brotli. Both do a similar job: reducing the size of a text by up to 70%.
Unless you want to squeeze out every bit of performance of your server, we recommend you don't spend too much time comparing the two. If only Gzip is enabled on your server, that's normally sufficient.
Most web hosts or CDNs have compression enabled by default. If compression is not enabled, follow the instructions below.
How to enable Gzip compression
Apache Server settings
If you have access to the server configuration file, the following code will enable Gzip for your server.
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/rss+xml
If you can't change the server settings, you can use the same code in your .htaccess file to enable compression.
Are you using an Nginx server? You can use this configuration to enable Gzip on your server:
gzip_types text/plain application/xml;
gzip_proxied no-cache no-store private expired auth;
More information about Gzip on Nginx
The cost of compression
You might think that compressing and decompressing also take time. That's true, but both the browser and the server are very efficient at this process. The time saved because of the reduced file size far outweighs the extra time it takes to compress and decompress the content.
How do I know if a browser can handle compression?
Browsers let the server know which types of compression it can handle. It uses the accept-encoding request header to tell the server if it can handle Gzip, Brotli, or both. Allmodern browsers support Gzip, and most also know Brotli.
If the browser accepts compressed files, the server will act accordingly and sent a nice and small file to the browser, significantly reducing the load times of your page.