Enabling brotli in your Azure CDN

TL;DR: If you are using Azure’s CDN and want to enable brotli you will need to create some custom rules that you can see at the end of the article.

Addy Osmani shared this tweet about CDNs that don’t support brotli and I though it could be interesting to tell how we enabled it on Azure CDN for https://dev.microsoftedge.com.

The first step is to compress the assets and configure IIS. This is relatively easy and you can learn how we did it here. The difficult part was getting the CDN to deliver the brotli-fy assets. Azure has Akamai and Verizon as CDN providers. Our website uses the Verizon one.

Initially, we tried using the “vary”: “accept-encoding” header, as fastly and stackpath (among others) recommend when dealing with CDNs and compressed assets. Unfortunately that didn’t work. Long story short (because it took longer that I wanted to), the solution was to create a couple of custom rules in their rule engine (available to anyone).

First you need to go to the external CDN management portal. You get access to it by clicking on “Manage” in your Azure CDN’s profile page.

Example of Azure CDN profile page and where the “Manage” button is

In the new page you need to go to “Rules Engine”, under “HTTP LARGE”

How to get to “Rules Engine” in the Azure CDN Management page

Once there, you are ready to create the rules. In our case we are also using zopfli for better gzip compression, so we end up creating two new rules. The trick is to create a different “Cache-Key” for gzip and brotli assets so the CDN stores the files separately. The anatomy of the brotli rule is as follows:

  • Detect if the request is for a file that is going to be compressed in the origin. In our case: css, html, ico, js, map, svg, txt, xml, webmanifest.
  • See if the browser supports brotli via the “Accept-Encoding” header via a regular expression.
  • If the above conditions are true, create a new “Cache-Key” (name_of_the_file_br) for the response of the origin and modify the “Accept-Encoding” header of the client to be just “br”.

We do exactly the same for gzip and we make sure that brotli has a higher priority by placing it at the bottom of the list of rules.

Zopfli rule
Brotli rule

After doing this, you just have to wait until the changes propagate and you should have brotli enabled in your site!