3

I have a tried to set up a very simple Sinatra and Webrick server working over https with a self signed certificate. I would like to redirect all http traffic to https, is this possible in this setup?

I have two Ruby files as below:

sinatra_ssl.rb

#sinatra_ssl.rb
require 'webrick/https'

module Sinatra
  class Application
    def self.run!
      certificate_content = File.open(ssl_certificate).read
      key_content = File.open(ssl_key).read

      server_options = {
        :Host => bind,
        :Port => port,
        :SSLEnable => true,
        :SSLCertificate => OpenSSL::X509::Certificate.new(certificate_content),
        :SSLPrivateKey => OpenSSL::PKey::RSA.new(key_content)
      }

      Rack::Handler::WEBrick.run self, server_options do |server|
        [:INT, :TERM].each { |sig| trap(sig) { server.stop } }
        server.threaded = settings.threaded if server.respond_to? :threaded=
        set :running, true
      end
    end
  end
end

EDIT: Added requirement of rack/ssl myapp.rb

    #myapp.rb
    require 'sinatra'
    require 'path/to/sinatra_ssl'
    require 'rack/ssl'

    use Rack::SSL

    set :server, 'WEBrick'
    set :ssl_certificate, "path/to/server.crt"
    set :ssl_key, "path/to/server.key"
    set :port, 8443

    get '/' do
        'Hello World!'
    end

Currently if I visit https://localhost:8443 I get the Hello World! message but if I visit http://localhost:8443 I get an ERR_EMPTY_RESPONSE as the server has no route for it.

Is there any way to do this redirect?

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Aly
  • 15,865
  • 47
  • 119
  • 191
  • I don't know how you deploy your applications but I usually deploy them behind a reverse proxy like nginx and there you can easily redirect all http traffic to https – Sir l33tname Jan 03 '15 at 12:49
  • @Sirl33tname Thanks, I will probably end up doing this but am just testing locally for now and was wondering if it was possible with WEBricks directly – Aly Jan 05 '15 at 11:03

2 Answers2

2

Can you consider using the middleware rack-ssl for the task? If then try this:

require 'rack/ssl'
use Rack::SSL
Jikku Jose
  • 18,306
  • 11
  • 41
  • 61
  • I have added this but still get ERR_EMPTY_RESPONSE when I try to access localhost over http, what I want is to redirect this to a https call in which is all works. – Aly Jan 03 '15 at 11:39
0

If you don't want SSL enforced via rack-ssl in your local environment then you can test for the environment in your config.ru and activate it accordingly:

require 'rack/ssl'

if ENV['RACK_ENV'] == 'production'
   use Rack::SSL
end
cacciatc
  • 9
  • 5