If you are using CloudFront for hosting static assets and having trouble with the CORS which prevents the icons from displaying properly on your website, in this post, I am going to show how to resolve this issue.
As you have already known, the main cause of CORS issue is because your fonts are loaded from a different domain than your website. For example, if your domain is http://example.com and you are using CloudFront domain (which is http://something.cloudfront.net), then you would have CORS issue. To solve this issue, the server must returns
Access-Control-Allow-Origin: * header in the response data (see some links at the bottom of this post for more information). However, CloudFront simply ignores this header when caching the assets and the problem still exists.
Perhaps after receiving tons of requests from the community, AWS has finally supported to solve this issue. Open your CloudFront distribution, you would notice a tab called Behaviors. A behavior is a way for you to tell CloudFront how to handle specific resource when going through AWS CloudFront. Our job is to add correct behavior for the fonts so that CloudFront can pass the needed header to the browsers.
Imagine that we are seeing the warning message as below:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://x3dskd59dg.cloudfront.net/assets/glyphicons-halflings-regular.woff. This can be fixed by moving the resource to the same domain or enabling CORS.
I would create new behavior with the following information:
Path Pattern: /assets/glyphicons-halflings-regular.woff
Forward Headers: Whitelist
Whitelist Headers: (This is the most important step, you need to select Origin header and add it to the whitelist in the right column)
All other fields can be left with default.
By doing this, CloudFront will allow the header
Access-Control-Allow-Origin: * to go through and visible to the browsers. You might need to Invalidate that font on CloudFront to clear the cache. Now, refresh the browsers and see how cool the icons are :)
In summary, two steps to solve CORS issue on CloudFront are:
Make change to Nginx or Apache configuration to add
Access-Control-Allow-Origin: *to the response data. You can take a look at some guides: http://enable-cors.org/server_apache.html and http://enable-cors.org/server_nginx.html
Add a behavior in CloudFront distribution, remember to whitelist the Origin header