WEBrick & Sinatra: how to redirect all HTTP traffic to https
I have an attempt to create a very simple Sinatra and Webrick server working on https with a self signed certificate. I would like to redirect all HTTP traffic to https, is it possible in this setup?
I have two Ruby files as shown 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 rack requirement / 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 message Hello World!
, but if I visit http://localhost:8443
I get ERR_EMPTY_RESPONSE
as the server has no route for it.
Is there a way to do this redirect?
+3
source to share