Skip to content

Instantly share code, notes, and snippets.

@shuber
Forked from speedmax/customdomain.rb
Created August 12, 2009 02:22
Show Gist options
  • Save shuber/166268 to your computer and use it in GitHub Desktop.
Save shuber/166268 to your computer and use it in GitHub Desktop.
DNS lookup for dynamic domains in rack applications
require File.dirname(__FILE__) + '/../../vendor/gems/net-dns-0.4/lib/net/dns/resolver'
# Custom Domain
# A Rack middleware to to resolve the custom domain to original subdomain
# for your multi telent application.
#
# It's all transperant to your application, it performs cname lookup and
# overwrite HTTP_HOST if needed
#
# www.example.org => example.myapp.com
#
class CustomDomain
@@cache = {}
def initialize(app, default_domain)
@app = app
@default_domain = default_domain
end
def call(env)
host = env['HTTP_HOST'].split(':').first
env['HTTP_X_FORWARDED_HOST'] = [host, cname_lookup(host)].join(', ') if custom_domain?(host)
@app.call(env)
end
def custom_domain?(host)
domain = @default_domain.sub(/^\./, '')
host !~ Regexp.new("#{domain}$", Regexp::IGNORECASE)
end
def cname_lookup(host)
unless @@cache[host]
Net::DNS::Resolver.new.query(host).each_cname do |cname|
@@cache[host] = cname if cname.include?(@default_domain)
end
end
@@cache[host]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment