Skip to content

Instantly share code, notes, and snippets.

@don
Created February 17, 2011 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save don/832071 to your computer and use it in GitHub Desktop.
Save don/832071 to your computer and use it in GitHub Desktop.
Rack Middleware to force all http requests to https
# Rack Middleware to force all http requests to https
# Alternately you could do this with an Apache or Nginx rewrite
#
# Install this middleware in conf/environments/production.rb
# config.middleware.use "ForceSSL"
#
# You can optionally set the host name for the redirect
# config.middleware.use "ForceSSL", "example.com"
#
class ForceSSL
def initialize(app, host = nil)
@app = app
@host = host
end
def call(env)
request = Rack::Request.new(env)
if request.scheme == 'http'
host = @host || request.host
[301, { 'Location' => "https://#{host}#{request.fullpath}" }, ['Redirecting...']]
else
@app.call(env)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment