GZIP and Brotli with .htaccess
Published
Updated
Compress responses for faster delivery.
fortrabbit sends responses uncompressed until `.htaccess` turns compression on. A few lines enable GZIP for every browser and Brotli for the browsers that accept it, which shrinks HTML, CSS and JS to a fraction of their size.
Turn on GZIP
Apache loads mod_deflate on fortrabbit, but no content type is compressed by default. Add this to the .htaccess in the root path:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml text/javascript
AddOutputFilterByType DEFLATE application/javascript application/json application/xml
AddOutputFilterByType DEFLATE application/rss+xml image/svg+xml
</IfModule>
Add the content types of the app, such as application/ld+json or text/markdown. Leave out images, video, PDF and woff2 fonts: they are compressed formats.
Turn on Brotli
mod_brotli is loaded too. Browsers that send Accept-Encoding: br then get Brotli, all others GZIP:
<IfModule mod_brotli.c>
AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/css text/xml text/javascript
AddOutputFilterByType BROTLI_COMPRESS application/javascript application/json application/xml
AddOutputFilterByType BROTLI_COMPRESS application/rss+xml image/svg+xml
SetEnvIfNoCase Accept-Encoding br no-gzip
</IfModule>
The last line switches GZIP off for requests that accept Brotli, so a response is not compressed twice. Place the Brotli block next to the GZIP block.
Check the response
curl -sI -H 'Accept-Encoding: gzip, br' https://www.example.com/
The response carries content-encoding: br or content-encoding: gzip. No such header means the content type is missing from the list.
Compression level
Apache compresses on the fly at the fastest setting, GZIP level 1 and Brotli quality 0, and .htaccess cannot change it. Both come out at about the same size: 44 kB for a 253 kB stylesheet. For static CSS and JS, precompress the files during the build at the highest level.