Rails assets Cloudfront fontawesome CORS

百般思念 提交于 2021-02-07 12:14:37

问题


I tried a lot of solutions found on stackoverflow/github for this issue but I can't get it to work.

I'm using font-awesome-rails and I precompile my assets for production. I've set CloudFront for my assets in my production config:

config.action_controller.asset_host = "https://XXXX.cloudfront.net"

When I load a page (from Chrome/Firefox because Safari is OK with CORS) I get this common error message :

Font from origin 'https://XXXX.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access.

I already tried to :

  1. Add the gem rack-cors and change my config.ru without success
  2. Set an after_filter to set the server headers without success
  3. Create an invalidation on CloudFront for the three fontawesome files without success

A workaround would be to remove the fontawesome gem and use instead:

<%= stylesheet_link_tag "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css", :media => "all" %>

But I'd rather find the issue.

Thanks


回答1:


I have had this issue and it was solved by doing the following changes. First of all, set a header on your http server add_header Access-Control-Allow-Origin *;

the complete configuration used:

location ~* \.(ttf|ttc|otf|eot|woff|woff2|svg|font.css)$ {
  add_header Access-Control-Allow-Origin *;
  expires max;
  allow all;
  access_log off;
  add_header Cache-Control "public";
}

and then create the invalidation on Cloudfront.

ps: I did not use rack-cors or any other gem




回答2:


This solution worked for me:

Your Bucket > Permissions > CORS Configuration and paste the following configuration:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

On your Rails project:

> vim environments/production.rb

add:

if ENV['CLOUDFRONT_ENDPOINT']
    config.action_controller.asset_host = proc { |source|
      if source =~ /^.*?\.(eot|ttf|woff|svg|otf)$/
        '//mydomain.com'
      else
        ENV.fetch('CLOUDFRONT_ENDPOINT') { 'https://cloudfrontname3244d4.cloudfront.net' }
      end
    }
end


来源:https://stackoverflow.com/questions/33003567/rails-assets-cloudfront-fontawesome-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!