2011-08-17 59 views
4

因此,我將我的rails(3.0.9)應用程序從一個域移動到另一個域。 Heroku的建議使用的before_filter在應用程序控制器,以確保每個人都對新的域結束了,就像這樣:Rails:重定向到特定域...但不覆蓋SSL?

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並且之前的篩選器嘗試將其重新放回到http?

你會如何解決這個問題?

回答

5

只需考慮當前的協議:

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

輝煌。謝謝 :) – Andrew

2

對於擴展的某一位全面的答案,整體看起來是這樣的;

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