轨道:重定向到特定域...但不覆盖 SSL?



所以,我移动我的rails(3.0.9)应用程序从一个域到另一个。Heroku建议在应用程序控制器中使用before_filter来确保每个人最终都在新域上,如下所示:

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

然而,在某些控制器视图上,我使用ssl_requirement,我相信它做同样的事情,但强制ssl协议。

对于请求处理之类的事情我不是很聪明。我的问题是,这两个是否会创建一个无限循环,其中SLL试图重定向到https,而before过滤器试图将其放回http?

你会如何解决这个问题?

请尊重当前协议:

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

对于一个具有一些可扩展性的综合答案,总体看起来是这样的;

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

这将把所有内容重定向到domain_to_redirect_to,除了domain_exceptions中的内容。

最新更新