Your website’s speed is important, as a faster website will dramatically decrease your bounce rate. Compressing your files on the server side is an easy way to reduce the size of your website, which speeds up loading.
Content Encoding, Explained
Whenever you try to access a website, your browser will send a GET request to the server, which responds with the code for the web page. This works, but sending the code over takes time, especially for mobile users on slow connections. Every kilobyte counts.
HTML is very repetitive. Every
<style> tag has a similar closing tag, and it’s all just text anyway. This means it compresses very easily.
Most browsers support compressed HTML, and they’ll tell you if they do with an
Accept-Encoding header in the GET request to your server:
Accept-Encoding: gzip, deflate
This means the client can decompress files compressed with either
deflate. Your server can listen for this header and then send back a HTML file compressed with
gzip with the header:
Enable Compression in Nginx
Luckily, this is a fairly simple process. Nginx has gzip encoding built in, you’ll just need to enable it by adding the following code to the config file, usually located at
This turns on the gzip module, and configures it to compress most text-based files.
Enabling Compression in Apache
For Apache, you’ll need to open up the Apache config file, usually located in one of the following places:
Then, make sure the following lines are uncommented to enable the deflate module:
LoadModule filter_module modules/mod_filter.so LoadModule deflate_module modules/mod_deflate.so
Save and reload Apache, and you can check if the module is loaded with:
apachectl -t -D DUMP_MODULES | grep deflate
If it is, you can open the config back up and turn on content encoding with the AddOutputFilter directive:
Checking Whether Compression Is Enabled
You can check if your web server is compressing properly from this online compression test, or by inspecting the response headers in the Chrome dev tools.
As you can see, compressing howtogeek.com results in a 77% savings, down to just 32 Kb.
Compressing Images Manually
Images work a bit different, as they’re not text, and don’t compress as easily. You can still compress images with gzip, but you won’t be saving much space.
Instead, you’ll want to employ traditional JPEG compression. JPEG has a quality setting, and a JPEG set to 70% quality is nearly indistinguishable from a 100% quality file, with massive space savings.
You can do this manually in Photoshop or another text editor, or you can process a whole folder of images at once with ImageMagick:
for f in *.jpg; do convert -quality 70 $f $f; done
If your images are still too big, you can drop the quality further, but 70% is a good mark for general compression. Make sure the resolution of your images isn’t unnecessarily large either.
Compression is just one part of speeding up your website. You can read our guide to speeding up a slow website to learn more.