簡體   English   中英

Rails:重定向到特定域……但不要覆蓋 SSL?

[英]Rails: Redirect to specific domain… but don't override SSL?

因此,我將我的 rails (3.0.9) 應用程序從一個域移動到另一個域。 Heroku 建議在應用程序 controller 中使用 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

但是,在某些 controller 視圖上,我正在使用ssl_requirement ,我相信它會做同樣的事情,但會強制使用 ssl 協議。

我對請求處理和所有那些爵士樂並不那么聰明。 我的問題是,這兩個是否會創建一個無限循環,其中 SLL 嘗試重定向到 https 並且之前的過濾器嘗試將其放回 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中的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM