David Walsh Blog

Serving Fonts from CDN

For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don’t work in Firefox or Internet Explorer (correctly so, by spec) though they do work (incorrectly so) in Webkit-based browsers. They actually require custom CORS configurations to display properly.  Here’s the code you’ll need to make that happen.

The .htaccess or httpd.conf Code

The code can be placed with the .htaccess file or httpd.conf file:

# Apache config
<FilesMatch ".(eot|ttf|otf|woff)">
	Header set Access-Control-Allow-Origin "*"

# nginx config
if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
	add_header Access-Control-Allow-Origin *;

This sets the Access-Control-Allow-Origin CORS configuration to allow pulling from all domains.  List specific domains by comma if you want to serve fonts up to only specific domains.  You’ll want to serve up all font types appropriately in the case that the browser prefers one type.

To ensure the header is set properly, you can check using the curl utility:

$ curl -I https://some.cdn.otherdomain.net/media/fonts/somefont.ttf

# Result
HTTP/1.1 200 OK
Server: Apache
X-Backend-Server: developer1.webapp.scl3.mozilla.com
Content-Type: text/plain; charset=UTF-8
Access-Control-Allow-Origin: *
ETag: "4dece1737ba40"
Last-Modified: Mon, 10 Jun 2013 15:04:01 GMT
X-Cache-Info: caching
Cache-Control: max-age=604795
Expires: Wed, 19 Jun 2013 16:22:58 GMT
Date: Wed, 12 Jun 2013 16:23:03 GMT
Connection: keep-alive

If you see Access-Control-Allow-Origin: * in the response, you’re golden!

This same strategy is used by Bootstrap CDN, so you know it’s good!