lyncd

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 bro 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 shared.mk, 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 bro:

for x in `find . -type f -name '*.gz'`; do gzip -dc $x | bro --force --output ${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>
<Files *.css.gz>
  AddType "text/css" .gz
  AddEncoding gzip .gz
</Files>

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

RewriteEngine On

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

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

Test

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

curl https://example.com/css/example.css -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 example.css.br on your server.

Filed under: Systems.  Tagged: , , .

No comments »

No comments yet.

Add a comment

You can also log in (or register) for easier commenting on lyncd.