开发者

Rails: Redirect to specific domain... but don't override SSL?

So, I'm moving my rails (3.0.9) app from one domain to another. Heroku suggests using a before_filter in the application controller to make sure that everyone ends up on the new domain, like so:

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

Howe开发者_JS百科ver, on certain controller views I'm using ssl_requirement, which I believe does the same thing but forces ssl protocol.

I'm not that smart about request handling and all that jazz. My question is, are these two going to create an infinite loop, where SLL tries to redirect to https and the before filter tries to put it back to http?

How would you solve this issue?


Just respect the current protocol:

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


For a comprehensive answer with some bit of extensibility, in totality 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 i.e. 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 what's in domain_exceptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜