-
-
Save almokhtarbr/2aee4b3295f6361d58cd16f18ddb5eff to your computer and use it in GitHub Desktop.
rack middleware to resolve a custom domain to an original subdomain in a multi-tenant application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| # | |
| # Base on : http://codetunes.com/2009/04/17/dynamic-cookie-domains-with-racks-middleware/ | |
| # | |
| class CustomDomain | |
| @@cache = {} | |
| def initialize(app, default_domain) | |
| @app = app | |
| @default_domain = default_domain | |
| end | |
| def call(env) | |
| host, port = env["HTTP_HOST"].split(':') | |
| # modify Environment variable HTTP_HOST if custom domain is found | |
| if custom_domain?(host) | |
| domain = cname_lookup(host) | |
| env["HTTP_HOST"] = port ? "#{domain}:#{port}" : domain | |
| env["HTTP_X_FORWARDED_HOST"] = host | |
| end | |
| @app.call(env) | |
| end | |
| def custom_domain?(host) | |
| domain = @default_domain.sub(/^\./, '') | |
| host !~ Regexp.new("#{domain}$", Regexp::IGNORECASE) | |
| end | |
| def cname_lookup(host) | |
| result = nil | |
| return host if @@cache[host] | |
| Net::DNS::Resolver.new.query(host).each_cname do |cname| | |
| result = $0 if cname.include?(@default_domain) | |
| end | |
| @@cache[host] = result | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment