Configuring WEBrick to use SSL in Rails 4

烈酒焚心 提交于 2019-11-28 05:27:21

I know you asked for WEBrick, and excuse me for suggesting something else, but I would really recommend you to use Thin ruby web server (faster and lighter), so you can also start SSL and meet your requirement as easy as:

$ thin start --ssl -p 3001

Just don't forget to add gem 'thin' in your Gemfile ;-)

Here's my solution which is compatible with both Rails 3 and 4.

Add the following code at the top of bin/rails:

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

module Rails
  class Server < ::Rack::Server
    def default_options
      ssl_default_options = {
        :Port => 443,
        :SSLEnable => true,
        :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
        :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.open(File.expand_path('../../config/cert/server_development.key', __FILE__)).read),
        :SSLCertificate => OpenSSL::X509::Certificate.new(File.open(File.expand_path('../../config/cert/server_development.crt', __FILE__)).read),
        :SSLCertName => [['CN', WEBrick::Utils::getservername]]
      }
      ENV['RAILS_SSL'] ? super.merge(ssl_default_options) : super
    end
  end
end

You obviously need to generate a self signed certificate or buy one.

Then when you want to start WebRick from command line use RAILS_SSL=true rails s. Usually you need sudo to listen on port 443 so you may want to append -p 3001 to change port.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!