您如何配置 WEBrick 以在 Rails 中使用 SSL? [英] How do you configure WEBrick to use SSL in Rails?
问题描述
在 Rails 3 之前,您可以修改脚本/服务器文件以添加 SSL 参数并告诉服务器命令使用 WEBrick 的 HTTPS 版本.现在所有这些脚本都没有了,有谁知道如何让它与 Rails 3 或 4 一起工作?
Prior to Rails 3, you could modify the script/server file to add in SSL parameters and tell the server command to use the HTTPS version of WEBrick. Now that all of those scripts are gone, does anyone know how to get this to work with Rails 3 or 4?
推荐答案
虽然 Rails 4 中的 scripts
目录消失了,但 bin
目录仍然存在.您可以通过编辑 bin/rails
脚本使 WEBrick 使用 SSL 证书.在 Rails 4 和 Ruby 2.1.1 上测试,安装了 rbenv.
While the scripts
directory in Rails 4 is gone, the bin
directory remains. You can get WEBrick working with an SSL certificate by editing the bin/rails
script. Tested on Rails 4 and Ruby 2.1.1, installed with rbenv.
Much of this is from this blog post and this Stack Overflow question.
#!/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 时,现在从应用程序目录启动 rails 服务器可以启动启用 SSL 的服务器,并且在省略环境变量时保留默认的 rails 设置.
Starting the rails server from the app directory works to start an SSL enabled server now when the SSL environment variable is set to true, and the default rails settings are retained when the environment variable is omitted.
$ 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 的 Utils::create_self_signed_cert
,如本答案所述:
If you don't want to use a pre generated certificate, you can use WEBrick's Utils::create_self_signed_cert
, as outlined in this answer:
配置 WEBrick 使用自动生成的自我-签署的 SSL/HTTPS 证书
这篇关于您如何配置 WEBrick 以在 Rails 中使用 SSL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!