我找到了這個問題的答案在這裏:http://codetunes.com/2009/04/17/dynamic-cookie-domains-with-racks-middleware/
該解決方案爲我,因爲我的應用程序是on Rails的2.3.5運行,它採用機架。請求來自Web服務器,遍歷中間件層並進入應用程序。所以這個中間件層檢測應用程序訪問的主機併爲請求設置cookie域。那就是:
# app/middlewares/set_cookie_domain.rb
class SetCookieDomain
def initialize(app, default_domain)
@app = app
@default_domain = default_domain
end
def call(env)
host = env["HTTP_HOST"].split(':').first
env["rack.session.options"][:domain] = custom_domain?(host) ? ".#{host}" : "#{@default_domain}"
@app.call(env)
end
def custom_domain?(host)
domain = @default_domain.sub(/^\./, '')
host !~ Regexp.new("#{domain}$", Regexp::IGNORECASE)
end
end
# turn it on in environment.rb
config.load_paths += %W(#{RAILS_ROOT}/app/middlewares)
# production.rb
config.middleware.use "SetCookieDomain", ".example.org"
.example.org是除非應用程序通過自定義域(如site.com)訪問將要使用的默認域,我們給它根據環境不同的值(生產/舞臺/開發等)。
# tests/integration/set_cookie_domain_test.rb (using Shoulda and Webrat)
require 'test_helper'
class SetCookieDomainTest < ActionController::IntegrationTest
context "when accessing site at example.org" do
setup do
host! 'example.org'
visit '/'
end
should "set cookie_domain to .example.org" do
assert_equal '.example.org', @integration_session.controller.request.session_options[:domain]
end
end
context "when accessing site at site.com" do
setup do
host! 'site.com'
visit '/'
end
should "set cookie_domain to .site.com" do
assert_equal '.site.com', @integration_session.controller.request.session_options[:domain]
end
end
context "when accessing site at site.example.org" do
setup do
host! 'site.example.org'
visit '/'
end
should "set cookie_domain to .example.org" do
assert_equal '.example.org', @integration_session.controller.request.session_options[:domain]
end
end
end