fearless_fool
fearless_fool

Reputation: 35189

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

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

The configuration

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.)

Upvotes: 3

Views: 978

Answers (2)

handler
handler

Reputation: 1483

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

Upvotes: 4

Neil Middleton
Neil Middleton

Reputation: 22238

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.

Upvotes: 0

Related Questions