Rails redirect_to从https(正确)redirect到http(不正确)?

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

 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而未login时,我将按照预期redirect到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. 

networking选项卡似乎表明我的redirect_to指向我的HTTP而不是HTTPS 。 当它遇到HTTP时,它会自动redirect到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 ,或者这是一个nginxconfiguration? 我认为使用login_path而不是login_url将解决这个问题,因为它应该是相对于基地,但似乎没有工作。


更新:

我也考虑过使用force_ssl ,但担心我正在用锤子敲一个图钉。 随意纠正我,如果我错了。

使用#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 

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

 config.force_ssl = true 

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