Codementor Events

Brotli compression on Nginx or Phoenix

Published Sep 18, 2018Last updated Oct 04, 2018

Brotli is a relatively new compression format that has two big advantages over gzip. It's faster at compressing things and it compresses them down to nearly ~25% smaller files!

It's slowly becoming more common to serve brotli compressed HTML, CSS, JS and JSON assets, as it speeds up page loads and decreases bandwidth costs.

Full screencast

If you're running Nginx in front of your server

If you're running Phoenix, Rails, Django, Node or anything else behind an Nginx proxy, then it's the Nginx server you'll need to configure for brotli, not your primary one. Here's how to do that on Ubuntu:

  • add the ppa:hda-me/nginx-stable repository

  • use apt-get to install brotli and nginx-module-brotli

  • update your nginx.conf to load ngx_http_brotli_filter_module.so and ngx_http_brotli_static_module.so

  • in the http block of nginx.conf turn on either brotli, brotli_static or both

  • Further instructions: example bash history and nginx.conf additions

If you're running Phoenix without a proxy in front of it

Since Elixir is so performant already, it's also not uncommon to run it without an Nginx proxy in front. For this kind of setup you'll have to do two things—enable brotli in Phoenix and work brotli compression into your workflow.

To turn brotli compression on in your endpoint.ex, just add brotli: true to the options passed to Plug.Static near the top of the file. That's all it takes.

Changing your static asset workflow to include brotli compression is a bit more work and there are a lot of ways to go about it. The simplest is probably using Brotli.js and calling it from your Brunch or Webpack configuration, but there are many Brotli implementations in different languages that might be a better alternative depending on the size and number of static assets you'll be compressing.

Originally published on Alchemist Camp

Discover and read more posts from Mark Wilbur
get started
post commentsBe the first to share your opinion
Show more replies