Add Brotli compression support to Apache for static assets and pages

The Apache web server doesn’t yet support stream compression using Brotli, but it’s easy to add support for static pages and assets such as CSS and Javascript files that you precompress. Browser support for Brotli is coming in Firefox 44 and in Chrome, and it provides about 15% savings versus precompressing with gzip/deflate.

First, download and build Brotli if it’s not already installed on your system. You’ll need to run make in the “dec”, “enc” and “tools” directories to build the brotli executable. A quick note here, if you’re using an older version of GCC you might get an error message because your g++ doesn’t support the -std=c++11 flag. I ran into this on an older Debian server (GCC 4.6.3 from 2011), changed -std=c++11 to -std=c++0x in the CXXFLAGS line of, and the build completed normally.

Compress and configure

Next, compress your files. If you already have static files compressed with the .gz extension, here’s a one-liner to recompress them all using brotli:

for x in `find . -type f -name '*.gz'`; do gzip -dc $x | brotli -fZ -o ${x%.gz}.br; done

Last, it’s time to add support for br-encoded files to Apache. You can do this server-wide, or in .htaccess. Here’s a quick .htaccess example that includes support for both Brotli and gzip pre-compressed files:

FileETag None

<Files *.js.gz>
  AddType "text/javascript" .gz
  AddEncoding gzip .gz
<Files *.css.gz>
  AddType "text/css" .gz
  AddEncoding gzip .gz

<Files *>
  AddType "text/javascript" .br
  AddEncoding br .br
<Files *>
  AddType "text/css" .br
  AddEncoding br .br

RewriteEngine On

RewriteCond %{HTTP:Accept-Encoding} br
RewriteCond %{REQUEST_FILENAME}.br -f
RewriteRule ^(.*)$ $ [L]

RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ $1.gz [L]


Finally, let’s test! An easy way to do this is using curl. For example:

curl -H 'Accept-Encoding: br' > file.out

Curl will download and save the br-encoded file example.css to file.out, which will be identical to on your server.

Filed under: Systems.  Tagged: , , .