如何将SSL添加到Rails应用程序?

时间:2014-04-03 08:29:14

标签: ruby-on-rails ssl

在我的项目中,我只想让我的每一个请求都通过SSL完成。怎么实现这个?我的意思是如何将SSL添加到Rails App?

我尝试添加

   config.force_ssl = true

到application.rb。但它显示我这样的错误。

无效请求:HTTP格式无效,解析失败。

/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/thin-1.6.1/lib/thin/request.rb:84:in `execute'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/thin-1.6.1/lib/thin/request.rb:84:in `parse'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/thin-1.6.1/lib/thin/connection.rb:41:in `receive_data'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/thin-1.6.1/lib/thin/backends/base.rb:73:in `start'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/thin-1.6.1/lib/thin/server.rb:162:in `start'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:in `run'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/server.rb:84:in `start'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands.rb:76:in `block in <top (required)>'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands.rb:71:in `tap'
/home/kamesh/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands.rb:71:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'

2 个答案:

答案 0 :(得分:4)

首先,您需要将ssl证书设置为您的应用程序。例如,如果您正在使用nginx,那么您需要制作类似nginx config

的内容

在application_controller.rb中使用过滤器或使用一些gem

class ApplicationController < ActionController::Base
  before_filter :redirect_to_https

  def redirect_to_https
    redirect_to :protocol => "https://" unless request.ssl?
  end
end

答案 1 :(得分:0)

我使用Rack :: SslEnforcer将SSL添加到我的rails应用程序

Rack::SslEnforcer Gem