CORS: You’re Doing It Wrong
Mike Ackerman, Former Senior Developer
Article Category:
Posted on
Do you really want to Access-Control-Allow-Origin = "*" ?
If you're serving font files from a CDN (content delivery network) and using an overly permissive CORS policy, you're doing it wrong. I'll show you how to serve those files with an appropriately restricted policy. When you're serving assets from a different domain (using a CDN), something like https://asdf98as9asd.cloudfront.net/assets
, you'll often see an error like: > Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://asdf98as9asd.cloudfront.net/assets/my-licensed-font.woff
. This can be fixed by moving the resource to the same domain or enabling CORS.. When you Google that error message, almost every result suggests that you add a web server configuration to allow serving your assets with a custom Header value of Access-Control-Allow-Origin = "*"
. However, if you're using licensed font files this is not what you should use! This setting would allow any other site to use your font assets by using the URL to your font file in their CSS.
Instead, you should consider setting this value to match your domain name: http://example.com
. Per the CORS spec, it supports "*"
, null
, or the exact domain. Here are my suggested configurations for Nginx and Apache to set the value to your server's domain name:
Nginx: #
server {
# other server configs here...
location ~* \.(eot|ttf|woff|woff2|otf|svg)$ {
add_header Access-Control-Allow-Origin $http_host;
}
}
Apache: #
<VirtualHost>
# other server configs here...
# Add CORS headers for font assets. Used when served by a CDN
SetEnvIf Request_Protocol ^HTTPS.* IS_HTTPS
SetEnvIf Host (.*) host_header=$1
<FilesMatch ".(eot|ttf|woff|woff2|otf|svg)">
Header set Access-Control-Allow-Origin "https://%{host_header}e" env=IS_HTTPS
Header set Access-Control-Allow-Origin "http://%{host_header}e" env=!IS_HTTPS
</FilesMatch>
</VirtualHost>
For more info on CORS, check out [Wikipedia](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) or [Mozilla Developers site](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).