redirecting from http://example.com to https://exa

2019-02-05 08:57发布

问题:

This question has been asked in various permutations, but I haven't found the right combination that answers my particular question.

The configuration

  • Rails 3.1 (allowing me to use force_ssl in my ApplicationController)
  • Hosted on Heroku Cedar (so I can't touch the middleware)
  • My SSL certs are registered for secure.example.com

I've already added force_ssl to my ApplicationController, like this:

# file: controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  force_ssl
end

The problem

Currently, if a user navigates to http://example.com, force_ssl switches to SSL, but since it's NOT secure.example.com, it presents a warning about an unverified security cert because it's using the default Heroku cert.

(I've verified that navigating to http://secure.example.com properly redirects to https://secure.example.com and uses the proper security cert. That's good.)

The question

How do I force http://www.example.com/anything and http://example.com/anything to redirect to http://secure.example.com/anything? (I'm assuming that force_ssl will handle the switch from http to https.) Since I cannot touch the middleware (recall that this is Heroku hosting), I assume I can do something like:

# file: controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  force_ssl
  before_filter :force_secure_subdomain

private
  def force_secure_subdomain
    redirect_to(something...) unless request.ssl?
  end
end

... but I haven't sufficiently grokked redirect_to and the request object to know what to write for something.... (I want to be sure that it handles query params, etc.)

回答1:

you can redirect to a different hostname by doing the following:

# file: controllers/application_controller.rb
class ApplicationController < ActionController::Base
  force_ssl :host => "secure.example.com"
end

see: rails force_ssl source for more info



回答2:

You should have a look at rack-rewrite - it's essentially Apache re-write but in Ruby form, and usable on Heroku.

This will allow you to create all sorts of Rack level rules and what redirections etc should occur and when.