Rails: redirecting to a specific domain ... but not overriding SSL?

So, I am moving the rails (3.0.9) application from one domain to another. Heroku suggests using before_filter in the application controller to make sure everyone ends in the new domain, for example:

before_filter :ensure_domain if Rails.env.production? APP_DOMAIN = 'www.newdomain.com' def ensure_domain if request.env['HTTP_HOST'] != APP_DOMAIN redirect_to "http://#{APP_DOMAIN}", :status => 301 end end 

However, on some controller views, I use ssl_requirement , which I believe does the same thing, but forces the ssl protocol.

I'm not so good at handling requests and all this jazz. My question is, will these two create an infinite loop where the SLL is trying to redirect to https and the before filter is trying to return it to http?

How would you solve this problem?

+4
source share
2 answers

Just follow the current protocol:

 redirect_to("#{request.protocol}#{APP_DOMAIN}", :status => 301) 
+5
source

To get a comprehensive answer with some degree of extensibility, in aggregate it looks something like this:

 class ApplicationController < ActionController::Base before_filter :redirect_to_example if Rails.env.production? # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception private # Redirect to the appropriate domain ie example.com def redirect_to_example domain_to_redirect_to = 'example.com' domain_exceptions = ['example.com', 'www.example.com'] should_redirect = !(domain_exceptions.include? request.host) new_url = "#{request.protocol}#{domain_to_redirect_to}#{request.fullpath}" redirect_to new_url, status: :moved_permanently if should_redirect end end 

This will redirect everything to domain_to_redirect_to , except in domain_exceptions .

+2
source

All Articles