在安全(https)上运行rails并通过webricks重定向非安全(http)请求以保护安全

Din*_*ini 1 ruby ssl ruby-on-rails webrick ruby-on-rails-3

我使用以下环境:

Server: Webrick
Rails: 3.2.6
Ruby: 1.9.3p555
Run Code Online (Sandbox Code Playgroud)

我在/ script/rails中添加了以下代码:

require 'rails/commands/server'
require 'rack'
require 'webrick'
require 'webrick/https'

if ENV['SSL'] == "true"
  module Rails
      class Server < ::Rack::Server
          def default_options
              super.merge({
                  :Port => 3000,
                  :environment => (ENV['RAILS_ENV'] || "production").dup,
                  :daemonize => false,
                  :debugger => false,
                  :pid => File.expand_path("tmp/pids/server.pid"),
                  :config => File.expand_path("config.ru"),
                  :SSLEnable => true,
                  :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
                  :SSLPrivateKey => OpenSSL::PKey::RSA.new(
                                   File.open("certs/project.key").read),
                  :SSLCertificate => OpenSSL::X509::Certificate.new(
                                   File.open("certs/project.crt").read),
                  :SSLCertName => [["CN", WEBrick::Utils::getservername]],
              })
          end
      end
  end
end

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)
require 'rails/commands'
Run Code Online (Sandbox Code Playgroud)

我在/config/environments/production.rb中添加了以下行:

config.force_ssl = true
Run Code Online (Sandbox Code Playgroud)

现在我尝试了以下尝试:

  1. 在3000上启动rails

    SSL=true rails s -e production -p 3000

它在https://project.com上运行rails,但在http://project.com上运行404错误

  1. 在443上启动rails并在脚本中提到相同的端口:

    rvmsudo rails s -p 443

  2. 使用两个不同的pid在80和443上启动rails:

    rvmsudo rails s -p 80 -P PID1 rvmsudo rails s -p 443 -P PID2

4.最后,我试图将请求从443和80转发到3000:

sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 3000
sudo iptables -t nat -I PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000
Run Code Online (Sandbox Code Playgroud)

此外,我也试图用薄宝石运行同样的东西,但结果是一样的.

eng*_*ave 8

冒着被焚烧和贬低的风险......

锤子只看到一切都是钉子不是一个有效的计划.有时当面对螺丝时你必须找到一把螺丝刀.

Webrick是rails web服务器最差的选项,只有在绝对必要的情况下才能使用.它太简单了,无法在你的Gemfile中放置瘦身或美洲狮,并在一个更快乐,线程更安全的世界中移动.

在这方面,这是你实现理智的九步计划.

第1步:停止.

第2步:想一想.

第3步:实现最佳实践是有原因的,例如完美的前向保密,代理rails应用程序的负载平衡,静态资产服务.

第4步:决定停止重新发明轮子并花时间学习你的手艺.

第5步:通过您的发行版的回购安装nginx

第6步:更改默认nginx主机以通过SSL为您的域提供服务.

第7步:将Puma添加到您的Gemfile,并捆绑更新

步骤8:设置puma init.d或upstart文件,使其在重新启动后保持不变

第9步:获利