【问题标题】:Rails redirect_to is redirecting from https (correct) to http (incorrect)?Rails redirect_to 正在从 https(正确)重定向到 http(不正确)?
【发布时间】:2014-02-20 02:32:27
【问题描述】:

在我的 Rails 4 应用程序中,我有一个 before_action 要求用户登录,如下所示:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :require_login

  def require_login
    unless logged_in?
      flash[:alert] = "You must be logged in to access this section."
      redirect_to login_path
    end
  end

  def logged_in?
    # more logic
  end
end

当我在没有登录的情况下访问example.com 时,我会按预期重定向到example.com/login。但是,我在控制台中看到了这个错误:

The page at 'https://example.com/login' was loaded over HTTPS, but displayed
insecure content from 'http://example.com/login': this content should also
be loaded over HTTPS.

网络选项卡似乎表明我的redirect_to 将我指向HTTP 而不是HTTPS。当它访问 HTTP 时,它会自动重定向到 HTTPS

Request URL:http://example.com/login
Request Method:GET
Status Code:301 Moved Permanently

# In the response headers:
Location:https://example.com/login

有没有办法告诉redirect_to 它应该使用HHTPS 而不是HTTP,或者这是一个nginx 配置?我认为使用 login_path 而不是 login_url 可以解决问题,因为它应该是相对于基础的,但这似乎不起作用。


更新:

我也想过使用force_ssl,但担心我会把锤子拿在图钉上。如果我弄错了,请随时纠正我。

【问题讨论】:

    标签: ruby-on-rails redirect nginx https ruby-on-rails-4


    【解决方案1】:

    在您的application.rb(或environment.rb)中,您可以设置

    config.force_ssl = true
    

    这将使 Rails 始终使用安全端点。

    【讨论】:

      【解决方案2】:

      使用#force_ssl:

      class ApplicationController < ActionController::Base
        force_ssl # use HTTPS for all actions
      
        protect_from_forgery with: :exception
        before_action :require_login
      
        def require_login
          unless logged_in?
            flash[:alert] = "You must be logged in to access this section."
            redirect_to login_path
          end
        end
      
        def logged_in?
          # more logic
        end
      end
      

      【讨论】:

      • force_ssl 会影响所有流量吗?我也想过这个解决方案,但担心我会把锤子拿在图钉上。
      • 它将影响ApplicationController 下的所有内容,因此可能会影响您的所有控制器。您应该将它添加到您想要的控制器中,我猜这将是您在其中定义 login 操作的控制器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2017-04-02
      相关资源
      最近更新 更多