Skip to content

Instantly share code, notes, and snippets.

@chrisvariety
Created May 2, 2012 13:49
Show Gist options
  • Save chrisvariety/2576644 to your computer and use it in GitHub Desktop.
Save chrisvariety/2576644 to your computer and use it in GitHub Desktop.
Rack Domain redirect
XXX.configure do
require 'rack_domain_redirect'
config.middleware.insert 0, Rack::DomainRedirect
end
module Rack
class DomainRedirect
attr_accessor :prefix
def initialize(app, &block)
@app = app
@prefix = 'www'
yield self if block_given?
end
def call(env)
parts = env['SERVER_NAME'].split('.')
suffix, chunk, prefix = parts.pop, parts.pop, parts.pop
if prefix != 'www' && prefix != 'staging' && prefix != 'couptopia'
destination = "#{env['rack.url_scheme']}://#{@prefix}.#{chunk}.#{suffix}"
destination << "#{env['PATH_INFO']}"
destination << "?#{env['QUERY_STRING']}" unless env['QUERY_STRING'].empty?
[301, {'Location' => destination}, ['See Ya!']]
else
@app.call(env)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment