HTTP Access Control to Multiple Origins

Here’s something that snuck in under my radar. Firefox supports the Cross-Origin Resource Sharing standard (CORS) for HTTP requests of some types of resource. This is a way for a remote host to control access to some types of resource.

The important one for me is web fonts, introduced in Firefox 3.1 (and likely video in the future). On a large site, it’s common to host media resources such as images, stylesheets, javascript, and now fonts, on one or more separate domains from the main domain used to access the page. As web fonts are subject to CORS, the appropriate Access Control headers need to be sent to the browser to allow the domain originating the request (the Origin) access to the resource.

The appropriate header here is Access-Control-Allow-Origin. This specifies which domain is allowed access to the resource. According to the developer document, acceptable values are either the URI of a specific allowable domain, or the wildcard character *. An example given being:


Allow multiple origin values

Apparently, the value can also be a comma separated list of domains, but I couldn’t get that to work in Firefox 3.5. So, how can you list multiple allowable domains? On Apache you can put this in the .htaccess file in your fonts directory:

<FilesMatch "\.(eot|otf|woff|ttf)$"> SetEnvIf Origin » "^http(s)?://(.+\.)?(domain1\.org|domain\.com)$" origin_is=$0 Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is </FilesMatch>

For files matching the common web font extensions, an origin_is environment variable is set when the Origin request header matches the value of the regular expression. In turn, the Access-Control-Allow-Origin header will only be set if the origin_is variable exists. origin_is is set to the value of the Origin header. The always condition ensures the header will be set for all responses, not just those with 2xx success codes (see Apache docs for more information about Header Directive conditions).