31

在 Rails 3 之前,您可以修改脚本/服务器文件以添加 SSL 参数并告诉服务器命令使用 HTTPS 版本的 WEBrick。现在所有这些脚本都消失了,有谁知道如何让它与 Rails 3 或 4 一起工作?

4

2 回答 2

27

虽然scriptsRails 4 中的目录消失了,但该bin目录仍然存在。bin/rails您可以通过编辑脚本让 WEBrick 使用 SSL 证书。在使用 rbenv 安装的 Rails 4 和 Ruby 2.1.1 上测试。

其中大部分来自这篇博客文章这个 Stack Overflow 问题

#!/usr/bin/env ruby

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 => 3001,
                  :environment => (ENV['RAILS_ENV'] || "development").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/server.key").read),
                  :SSLCertificate => OpenSSL::X509::Certificate.new(
                                   File.open("certs/server.crt").read),
                  :SSLCertName => [["CN", WEBrick::Utils::getservername]],
              })
          end
      end
  end
end

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'
require 'rails/commands'

当 SSL 环境变量设置为 true 时,从 app 目录启动 rails 服务器现在可以启动启用 SSL 的服务器,并且当省略环境变量时保留默认的 rails 设置。

$ SSL=true rails s
=> Booting WEBrick
=> Rails 4.1.0 application starting in development on https://0.0.0.0:3001
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
[2014-04-24 22:59:10] INFO  WEBrick 1.3.1
[2014-04-24 22:59:10] INFO  ruby 2.1.1 (2014-02-24) [x86_64-darwin13.0]
[2014-04-24 22:59:10] INFO  
Certificate:
    Data:
...

如果您不想使用预先生成的证书,可以使用 WEBrick's Utils::create_self_signed_cert,如本答案中所述:

配置 WEBrick 以使用自动生成的自签名 SSL/HTTPS 证书

于 2014-04-25T03:57:26.773 回答
22

WEBrick 上 SSL/HTTPS 的替代方案:Thin 上的 SSL/HTTPS

作为尝试将 WEBrick 设置为在 Rails 应用程序中使用 HTTPS/SSL 的替代方法,您可以尝试改用瘦服务器,因为它提供了开箱即用的设置 HTTPS/SSL 的便捷选项。

安装薄

首先,将 Thin 作为 gem 添加到您的 Gemfile 中:

gem 'thin'

然后从命令行运行bundle install

在开发环境中使用精简 HTTPS/SSL

如果您只想在本地开发环境中使用 HTTPS/SSL 测试您的 Rails 应用程序,那么您只需运行

thin start --ssl

我必须强调,这不适合生产环境,因为您需要使用来自证书颁发机构的有效 SSL 证书才能使 SSL/HTTPS 连接可验证且安全。

附加选项

您还可以将其他选项传递给 Thin。您可以通过运行获取它们的完整列表thin --help。例如,我喜欢指定我自己的 ip-address 和 port,以及将 Thin 守护到后台进程中:

thin start --ssl \
  --address <ip-address> \
  --port <port> \
  --daemonize

将瘦 HTTPS/SSL 与 SSL 证书一起使用

如果您想告诉 Thin 使用 SSL 证书(例如,您从有效的证书颁发机构获得的证书),那么您可以使用以下选项:

thin start --ssl \
  --ssl-cert-file <path-to-public-certificate> \
  --ssl-key-file <path-to-private-key>
于 2014-04-17T19:18:27.477 回答