Serving web fonts via AWS S3 and Cloudfront
Typically when using custom fonts on a client's website we'll utilize a third-party service such as TypeKit or Fonts.com. Unfortunately, using a third-party service wasn't an option this latest time around.
In the interest of speed we host all of our assets on S3 which is then distributed world-wide via Cloudfront. Fonts were no exception however we ran into a few gotchas along the way.
As it turns out, web fonts are subject to Cross-Origin Resource Sharing (CORS). CORS is a way for a remote host to control access for certain types of resources. Certain browsers (Chrome, Safari) will ignore CORS and make the request while others (IE, Firefox).
To ensure that all browsers are able to retrieve the fonts you must follow the instructions below:
S3
- Select the bucket in question.
- Select the "Properties" tab.
- Expand the "Permissions" section.
- Click the button "Edit CORS Configuration".
- Enter the following into the box (edit for your domain): https://gist.github.com/tmilewski/bfaebc876cc116623e86
Cloudfront
The S3 implementation is easy enough but Cloudfront (or any CDN) has a major gotcha which lead to a lot of confusion and frustration:
HTTP/HTTPS
In the S3 example we allowed requests to come from both HTTP and HTTPS. When a CDN enters the picture it will cache the response from S3. Therefore, if you request the font with HTTPS any future CORS request from HTTP will sadly fail (and vice-versa).
Pick one and stick with it.
Related protips:
Written by Tom Milewski
Related protips
5 Responses
Thank you so much for this!
Thanks!
Thanks. It was really helpful
If you set up the 'behavior' in cloudfront to forward the Origin header using the whitelist, cloudfront will cache separate copies for http and https, but both will work at the same time. (Still, if possible, stick to one to improve caching ;)
Thank you so much. I was facing problem loading fonts via Cloudfront. Your article solved my problem. I really appreciate your contribution