简体   繁体   中英

WEBrick & Sinatra: how to redirect all http traffic to https

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?

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

require 'rack/ssl'
use Rack::SSL

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM