问题
I need to make http://example.com go to https://www.example.com. right now it's warning in the browser. I followed: http://www.simonecarletti.com/blog/2011/05/configuring-rails-3-https-ssl/
loading from /lib/middleware (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
production 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:
If you can get your webserver to do the redirect, that's usually best. If you're on Heroku or a similar platform where you can't get the webserver to redirect for you, make these changes:
Change the middleware line to be:
config.middleware.insert_before Rack::SSL, "WwwMiddlewareRedirect"
Then in your gemfile, include:
gem 'rack-ssl', :require => 'rack/ssl'
回答2:
Unless I'm misunderstanding, I think you are using the < 3.1 instructions for a 3.1 app. In 3.1 you only need to set force_ssl to true and it will result in the behavior you desire.
来源:https://stackoverflow.com/questions/7959860/how-to-perform-301-before-force-ssl-rails-3-1