2012-11-15 19 views

回答

2

您可以創建一個新的中間件這個

class SubdomainToWwwMiddleware 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    request = Rack::Request.new(env) 
    if !request.host.starts_with?("www.") 
     [301, { "Location" => request.url.gsub(/\/\/([^\.]*)/, "//www") }, self] 
    else 
     @app.call(env) 
    end 
    end 
end 

這是未經測試,但應該把你在正確的方向。您可能希望添加一個條件來檢查不僅是爲www.example.com,而且還有example.com。在這種情況下,上面的中間件可能會炸燬。

你可以把這個在/lib/middleware/subdomain_to_www_middleware.rb,加

config.autoload_paths += %W(#{ config.root }/lib/middleware) 

config/application.config,並

config.middleware.use "SubdomainToWwwMiddleware" 

config/environments/production.rb

+0

我跟着你的步驟,並得到了錯誤:TypeError(無法將Regexp轉換爲字符串): lib/middleware/subdo main_to_www_middleware.rb:9:'gsub' lib/middleware/subdomain_to_www_middleware.rb:9:在'call' –