Fonts blocked by CORS policy on localhost: How to fix that

CORS Policy - 'Access-Control-Allow-Origin'
0 0 vote
Article Rating

I’m using MAMP Pro and have a separate Host setup for each of my website projects.

This let’s me navigate to https://local.mydomain.com instead of https://localhost:8888/mywebsitedirectory.

You can easily set up local.mydomain.com to be a.b.c if you wanted; this is my convention for projects. I like to separate local dev with production and sandbox/staging sites.

Since i decided to serve fonts locally as web fonts instead of grabbing them from Google or TypeKit or wherever, i noticed this while looking in DevTools:

Access to Font at
'http://localhost/toolongname.font' from origin 'http://local.macariojames.com' 
has been blocked by CORS Policy: 
No 'Access-Control-Allow-Origin' header 
is present on the requested resource. Origin 'http://local.macariojames.com' is 
therefore not allowed access.

The issue as it states is there’s no header in the server’s configuration (Apache or nginx) to tell the server to allow the serving of fonts across domains, hence the CORS policy issue.

Relatively simple fix as long as you have permission to edit your .htaccess or httpd.conf file depending on server type.

Here’s code for both:

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

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

Ta-da. Save your file, restart server (if applicable), and try again. Hope that helps. Cheers and peace.

0 0 vote
Article Rating

If you found this post useful ...

Buy Me a Coffee logo
Wondering why you keep seeing lower-cased 'i' in my posts? Read -> Why ‘i’ is not capitalized
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x