All the assets except for the fonts load nicely, and whenever I go to my site I keep getting messages like this one:
Access to Font at 'https://xxxxxxxxxx.cloudfront.net/assets/fontawesome-webfont.woff2' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.
As you can see CURL command indicates that no headers are present.
curl -H "Origin: https://example.com" -I https://xxxxxxxxx.cloudfront.net/assets/fontawesome-webfont.woff2
HTTP/1.1 200 OK
Content-Length: 77160
Connection: keep-alive
Status: 200 OK
X-Rack-Cache: stale, valid, store
Cache-Control: public, must-revalidate
Date: Fri, 14 Apr 2017 08:01:26 GMT
X-Content-Digest: d6f48cba7d076fb6f2fd6ba993a75b9dc1ecbf0c
ETag: "2adefcbc041e7d18fcf2d417879dc5a09997aa64d675b7a3c4b6ce33da13f3fe"
X-Runtime: 0.366713
X-Request-Id: 87c9d883-e443-4756-86f9-66b40ed573f6
X-Powered-By: Phusion Passenger Enterprise 5.1.2
Server: nginx/1.10.2 + Phusion Passenger 5.1.2
Via: 1.1 vegur, 1.1 f0eecbf6390179377707b707ebaa1e8b.cloudfront.net (CloudFront)
Age: 86645
Vary: Accept-Encoding
X-Cache: Hit from cloudfront
X-Amz-Cf-Id: FNjQGvROcAdqT6u6PaN3OgEE34mnSsixHNm6WqzWq2boWWYYzVmZPw==
Here's AWS Origin configuration

And this is the behaviour that includes the above origin:

I even included rack-cors to the initializers within the project for the purpose but with no luck.
if defined? Rack::Cors
Rails.configuration.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/assets/*', headers: :any, methods: [:get, :post, :delete, :put, :patch, :options, :head], max_age: 0
end
end
end
Why is this so and how can I fix it? Thank you in advance.
As of version 5.0, Rails allows for setting custom HTTP Headers for assets and you don't have to add dependencies like the font_assets gem. In order to set Access-Control-Allow-Origin to your font, just add the following codde to config/environments/production.rb:
config.public_file_server.headers = {
'Access-Control-Allow-Origin' => '*'
}
Update on 07/25/2018:
The header value could also be a specific domain, like the following:
config.public_file_server.headers = {
'Access-Control-Allow-Origin' => 'https://www.example.org'
}
I think most common solution is to use font_assets gem. Configuration is pretty straightforward. In config/environments/production.rb add this
config.font_assets = "http://YOUR_ASSET_HOST"
Unfortunately I cannot explain this in more details, but that's what we use in our project and it works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With