Rails - 如何从http://example.com重定向到https://www.example.com

AnA*_*ice 33 dns ruby-on-rails heroku ruby-on-rails-3

我正在寻找如何清理我的应用程序的URL.我的应用程序由Heroku上的Rails 3提供支持.

所需的URL是 https://www.example.comite.com

我想将与上述不同的所有网址重定向到该网址.这是Rails还是DNS?

错误的网址:

https://example.comite.com
http://www.example.comite.com
http://example.comite.com
Run Code Online (Sandbox Code Playgroud)

如果有任何结尾,就像http://www.example.comite.com/photo/1要使用路径重定向的url 一样:https://www.example.comite.com/photo/1

Jon*_*Jon 48

作为user2100689答案的扩展,在Rails 3+中你可以config.force_ssl = trueconfig/environments/production.rb中使用

该行可以如下取消注释

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
Run Code Online (Sandbox Code Playgroud)


edg*_*ner 18

DNS记录不能定义的协议域,因此,你不能重定向http://https://通过DNS.通过Web服务器配置执行此操作不可移植,难以执行,容易出错且只是过时了.这是Rails路由器最好的处理工作.

# beginning of routes.rb 
match "*path" => redirect("https://www.mysite.com/%{path}"), :constraints => { :protocol => "http://" }
match "*path" => redirect("https://www.mysite.com/%{path}"), :constraints => { :subdomain => "" }
Run Code Online (Sandbox Code Playgroud)


use*_*960 7

因为这是Heroku,所以你不能使用apache或nginx配置.你可以做的是在你的ApplicationController中放一个before_filter,假设你有3个或更多如下控制器,尽管它们当然会在不同的文件中

class ApplicationController < ActionController::Base
    def redirect_https        
        redirect_to :protocol => "https://" unless request.ssl?
        return true
    end
    before_filter :redirect_https
end
class TypicalController < ApplicationController
    def blah
    end
end
class HomePageController < ApplicationController
    skip_before_filter :redirect_https
end
Run Code Online (Sandbox Code Playgroud)

您可能还需要在使用设计时稍微改变一下您的路线,但我怀疑这只是我们这样做的方式所以我不会在这里详细介绍这些细节,并且我修改了上面的代码以避免这种复杂化.

快乐的黑客.


Rob*_*rty 7

Rails 3.1.0和更高版本具有force_ssl,这是一种控制器方法,将在非开发环境中重定向到https.

http://api.rubyonrails.org/classes/ActionController/ForceSSL/ClassMethods.html

将它放在要重定向的每个控制器中,或者更好的是,将它放在ApplicationController中:

应用程序/控制器/ application.rb中:

class ApplicationController < ActionController::Base
  # ...
  force_ssl
  # ...
end
Run Code Online (Sandbox Code Playgroud)

这总是包含在您的应用中是一件好事(当然,您必须获得证书).HTTPS无处不在!


小智 7

你可以随时把它扔进你的production.rb ...... config.use_ssl = true

  • 使用Rails 5(也可能是旧版本),`use_ssl`将不执行任何操作.`force_ssl`是必须设置的选项. (4认同)