2011-10-31 13 views
1

我需要使http://example.com轉到https://www.example.com。現在它在瀏覽器中發出警告。我跟着:http://www.simonecarletti.com/blog/2011/05/configuring-rails-3-https-ssl/如何在force_ssl之前執行301? Rails 3.1

從/ lib目錄/中間件負載(Rails的3.1)

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

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

    def each(&block) 
    end 
end 

生產ENV

Example::Application.configure do 

    config.force_ssl = true 

    # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 
    # config.force_ssl = true 

    config.middleware.use "WwwMiddlewareRedirect" 
end 

回答

1

如果你可以讓你的網絡服務器做重定向,那通常是最好的。如果你在Heroku或類似的平臺,在這裏你不能讓Web服務器爲您重定向,進行這些更改:

更改中間件線爲:

config.middleware.insert_before Rack::SSL, "WwwMiddlewareRedirect" 

然後在你的Gemfile,包括:

gem 'rack-ssl', :require => 'rack/ssl' 
+0

只是Gem'rack-ssl''在Gemfile中爲我工作 –

0

除非我的誤解,我認爲你正在使用的< 3.1的說明一個3.1應用程序。在3.1中,你只需要將force_ssl設置爲true,它就會導致你想要的行爲。

+0

該證書適用於www.example.com而不是example.com,例如https://amazon.com – tidelake

+0

啊我明白了。那麼FWIW,我可能會做這個重定向在網絡服務器(Nginx)的水平。 (但我意識到我不知道你的確切情況,所以也許這不是理想的) –

+0

另外,certs通常來自example.com和www.example.com ...我認爲即使是便宜的。 –

相關問題