2014-09-20 49 views
11

我無法獲得Access-Control-Allow-Origin在Chrome中顯示 - 我的最終目標是使用Rails爲CORBA配置字體,因此它可以在帶有CloudFront的production中運行。但現在,我只想讓它在development中工作。我可以通過curl看到標題,但不是Chrome。如何使用rails,nginx和passenger配置`Access-Control-Allow-Origin`?

我使用Rails 4.0,我已經嘗試了所有的以下...

我已經配置Gemfileapplication.rbthe rack-cors example for rails 4

的Gemfile

gem 'rack-cors', '~> 0.2.9', require: 'rack/cors' 

配置/application.rb

config.middleware.insert_before 'ActionDispatch::Static', 'Rack::Cors' do 
    allow do 
     origins '*' 
     resource '*', 
      :headers => :any, 
      :methods => [:get, :options, :head] 
    end 
end 

導軌控制檯

2.0.0-p481 :001 > Rails.env 
=> "development" 
2.0.0-p481 :002 > Hello::Application.config.serve_static_assets 
=> true 

的bash

curl -i http://localhost:5000/assets/OpenSans-Regular-webfont.woff 

Content-Type: application/font-woff 
Content-Length: 22660 
Connection: keep-alive 
Status: 200 OK 
Cache-Control: public, must-revalidate 
Last-Modified: Wed, 30 Apr 2014 23:51:57 GMT 
ETag: "467b34801137bd4031e139839ad86370" 
X-Request-Id: c4b07b4d-1c43-44ea-9565-dfda66378f98 
X-Runtime: 0.046007 
X-Powered-By: Phusion Passenger 4.0.50 
Date: Sat, 20 Sep 2014 04:39:38 UTC 
Server: nginx/1.6.1 + Phusion Passenger 4.0.50 

curl -i -H "Origin: http://localhost:5000" http://localhost:5000/assets/OpenSans-Regular-webfont.woff 

Content-Type: application/font-woff 
Content-Length: 22660 
Connection: keep-alive 
Status: 200 OK 
Cache-Control: public, must-revalidate 
Last-Modified: Wed, 30 Apr 2014 23:51:57 GMT 
ETag: "467b34801137bd4031e139839ad86370" 
Access-Control-Allow-Origin: http://localhost:5000 # adding 
Access-Control-Allow-Methods: GET, OPTIONS, HEAD  # -H 
Access-Control-Max-Age: 1728000      # produced 
Access-Control-Allow-Credentials: true    # these 
Vary: Origin           # headers 
X-Request-Id: b9666f30-416d-4b5b-946a-bdd432bc191c 
X-Runtime: 0.050420 
X-Powered-By: Phusion Passenger 4.0.50 
Date: Sat, 20 Sep 2014 03:45:30 UTC 
Server: nginx/1.6.1 + Phusion Passenger 4.0.50 

鉻(V37)開發工具>網絡> OpenSans-常規webfont.woff>頁眉>響應頭

HTTP/1.1 304 Not Modified 
Connection: keep-alive 
Status: 304 Not Modified 
Cache-Control: no-cache 
X-Request-Id: ac153b8c-e0cb-489d-94dd-90aacc10d715 
X-Runtime: 0.116511 
X-Powered-By: Phusion Passenger 4.0.50 
Date: Sat, 20 Sep 2014 03:41:53 UTC 
Server: nginx/1.6.1 + Phusion Passenger 4.0.50 

我也試過以下的替代品,因爲每various sources

config.middleware.insert_before 'ActionDispatch::Static', 'Rack::Cors' do 
config.middleware.insert_after Rails::Rack::Logger, Rack::Cors do 
config.middleware.insert_before Warden::Manager, Rack::Cors do 
config.middleware.insert 0, Rack::Cors do 
config.middleware.use Rack::Cors do 

我也試過以下,以applications.rb,按How to Display FontAwesome in Firefox Using Rails and CloudFront

config.assets.header_rules = { 
    :global => {'Cache-Control' => 'public, max-age=31536000'}, 
    :fonts => {'Access-Control-Allow-Origin' => '*'} 
} 

我也試過在config.ru以下,如每個CloudFront CDN with Rails on Heroku

require 'rack/cors' 
use Rack::Cors do 
    allow do 
     origins '*' 
     resource '*', :headers => :any, :methods => :get 
    end 
end 

束EXEC耙中間件

use Rack::Cors 
use Rack::Sendfile 
use ActionDispatch::Static 
use Rack::Lock 
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007f9ec21590b0> 
use Rack::Runtime 
use Rack::MethodOverride 
use ActionDispatch::RequestId 
use Rails::Rack::Logger 
use ActionDispatch::ShowExceptions 
use ActionDispatch::DebugExceptions 
use ActionDispatch::RemoteIp 
use ActionDispatch::Reloader 
use ActionDispatch::Callbacks 
use ActiveRecord::Migration::CheckPending 
use ActiveRecord::ConnectionAdapters::ConnectionManagement 
use ActiveRecord::QueryCache 
use ActionDispatch::Cookies 
use ActionDispatch::Session::CookieStore 
use ActionDispatch::Flash 
use ActionDispatch::ParamsParser 
use Rack::Head 
use Rack::ConditionalGet 
use Rack::ETag 
use Warden::Manager 
use OmniAuth::Strategies::Facebook 
run Hello::Application.routes 

我還試圖font_assets無濟於事。

回答

15

Server行讓我覺得,也許這些資產不被Rails的處理,而是由nginx

enter image description here

這意味着,標頭必須由nginx,不是Rails的加入,因此我們需要配置nginx。原來,the ability to configure nginx is possible as of Passenger 4.0.39 - (here is the corresponding Git diff)。相應的文件可在Passenger Standalone, under Advanced configuration獲得。

文檔中的一個重要提示:原始配置模板文件可能會不時變化,例如,因爲Phusion Passenger引入了新功能。如果您的配置模板文件不包含所需的更改,那麼這些新功能可能無法正常工作。在最糟糕的情況下,Standalone甚至可能會發生故障。因此,每次升級Phusion Passenger時,都應檢查原始配置模板文件是否已更改,並將所有更改歸併到您自己的文件中。

關於該注意事項,除了配置文件的可定製副本之外,創建一個「原始」副本,無論何時升級Passenger,都可以使用diff

的bash

cp $(passenger-config about resourcesdir)/templates/standalone/config.erb config/nginx.conf.erb 
cp config/nginx.conf.erb config/nginx.conf.erb.original 

接着,在添加Procfile--nginx-config-template config/nginx.conf.erbweb線。

Procfile

web: bundle exec passenger start -p $PORT --max-pool-size 3 --nginx-config-template config/nginx.conf.erb 

配置/ nginx.conf.erb

接着,通過發現如下所示的塊編輯配置文件config/nginx.conf.erb

location @static_asset { 
     gzip_static on; 
     expires max; 
     add_header Cache-Control public; 
     add_header ETag ""; 
    } 

...並添加兩條Access-Control行:

location @static_asset { 
     gzip_static on; 
     expires max; 
     add_header Cache-Control public; 
     add_header ETag ""; 
     add_header Access-Control-Allow-Origin *; 
     add_header Access-Control-Request-Method *; 
    } 

就是這樣。這將在production工作,但不在development,由於config.assets兩者之間的差異。

的配置差異

diff不應該現在返回任何東西,但如果任何未來更新的乘客包括更改這個文件,你就知道了。

diff $(passenger-config about resourcesdir)/templates/standalone/config.erb config/nginx.conf.erb.original 

nginx的文檔

今後的改進

  • 限制Allow-Origin
  • 限制Request-Method
  • 限制兩個頭,只是字體
1

我不知道這是答案,但它看起來像你也可以嘗試使用after_filter用最簡單的方法:

headers['Access-Control-Allow-Origin'] = '*' 
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS' 
headers['Access-Control-Request-Method'] = '*' 
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' 
... 
2

YES!最後。

user664833的answer above是偉大的,除了我找不到我的Passenger配置文件進行編輯。

托馬斯·奈的答案here給出完整的文件創建在配置/ nginx.conf.erb:

########################################################################## 
# Passenger Standalone is built on the same technology that powers 
# Passenger for Nginx, so any configuration option supported by Passenger 
# for Nginx can be applied to Passenger Standalone as well. You can do 
# this by direct editing the Nginx configuration template that is used by 
# Passenger Standalone. 
# 
# This file is the original template. DO NOT EDIT THIS FILE DIRECTLY. 
# Instead, make a copy of this file and pass the `--nginx-config-template` 
# parameter to Passenger Standalone. 
# 
# Learn more about using the Nginx configuration template at: 
# https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template 
# 
# *** NOTE *** 
# If you customize the template file, make sure you keep an eye on the 
# original template file and merge any changes. New Phusion Passenger 
# features may require changes to the template file. 
############################################################## 

<%= include_passenger_internal_template('global.erb') %> 

worker_processes 1; 
events { 
    worker_connections 4096; 
} 

http { 
    <%= include_passenger_internal_template('http.erb', 4) %> 

    ### BEGIN your own configuration options ### 
    # This is a good place to put your own config 
    # options. Note that your options must not 
    # conflict with the ones Passenger already sets. 
    # Learn more at: 
    # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template 

    ### END your own configuration options ### 

    default_type application/octet-stream; 
    types_hash_max_size 2048; 
    server_names_hash_bucket_size 64; 
    client_max_body_size 1024m; 
    access_log off; 
    keepalive_timeout 60; 
    underscores_in_headers on; 
    gzip on; 
    gzip_comp_level 3; 
    gzip_min_length 150; 
    gzip_proxied any; 
    gzip_types text/plain text/css text/json text/javascript 
     application/javascript application/x-javascript application/json 
     application/rss+xml application/vnd.ms-fontobject application/x-font-ttf 
     application/xml font/opentype image/svg+xml text/xml; 

    <% if @app_finder.multi_mode? %> 
     # Default server entry for mass deployment mode. 
     server { 
      <%= include_passenger_internal_template('mass_deployment_default_server.erb', 12) %> 
     } 
    <% end %> 

    <% for app in @apps %> 
    server { 
     <%= include_passenger_internal_template('server.erb', 8, true, binding) %> 
     <%# <%= include_passenger_internal_template('rails_asset_pipeline.erb', 8, false) %1> %> 

     ### BEGIN your own configuration options ### 
     # This is a good place to put your own config 
     # options. Note that your options must not 
     # conflict with the ones Passenger already sets. 
     # Learn more at: 
     # https://www.phusionpassenger.com/library/config/standalone/intro.html#nginx-configuration-template 
     # Rails asset pipeline support. 
     location ~ "^/assets/.+-([0-9a-f]{32}|[0-9a-f]{64})\..+" { 
      error_page 490 = @static_asset; 
      error_page 491 = @dynamic_request; 
      recursive_error_pages on; 

      if (-f $request_filename) { 
       return 490; 
      } 
      if (!-f $request_filename) { 
       return 491; 
      } 
     } 
     location @static_asset { 
      gzip_static on; 
      expires max; 
      add_header Cache-Control public; 
      add_header ETag ""; 
      if ($http_origin ~* ((https?:\/\/[^\/]*\.herokuapp\.com(:[0-9]+)?))) { 
       add_header 'Access-Control-Allow-Origin' "$http_origin"; 
       add_header 'Access-Control-Allow-Credentials' 'true'; 
       add_header 'Access-Control-Allow-Methods' 'GET, HEAD'; 
       add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; 
      } 
     } 
     location @dynamic_request { 
      passenger_enabled on; 
     } 

     ### END your own configuration options ### 
    } 
    passenger_pre_start <%= listen_url(app) %>; 
    <% end %> 

    <%= include_passenger_internal_template('footer.erb', 4) %> 
} 

Procfile應包括線路:

web: bundle exec passenger start -p $PORT --max-pool-size 3 --nginx-config-template config/nginx.conf.erb

您還需要按照Guapolo's answer

配置您正在爲資產提供服務的Cloudfront CDN Configure CORS Cloudfront

在你的發行版中,給你的CORS悲傷,轉到行爲選項卡和一個新的行爲,選擇資產的路徑,即/assets/icons.ttf和白名單'Origin'按上述圖片。

在失效分發中,您可能還需要在無效標籤中「使無效」舊的緩存資源,即放入檢查器的完整資產和緩存名稱,並使其無效。處理完成後,使用配置部署應用程序並重新啓動heroku。您需要打開檢查器,然後'清空緩存並重新加載'頁面。

希望這是有效的 - 聽起來乘客配置會不時變化,所以我們可能會發現這會中斷,並且需要更新答案以反映新的配置。

相關問題