Thursday, June 4, 2009

multiple hosts/domains and proxied requests in rails

Imagine you have an invoicing application where each client has its own subdomain like http://huberry.ordersapp.com. You'd like to allow clients to use their own domains/uris to access your application like:

http://huberryorders.com
http://orders.huberry.com
http://huberry.com/orders

The proxy gem/plugin solves this problem.

gem install shuber-proxy --source http://gems.github.com
OR
script/plugin install git://github.com/shuber/proxy.git

The proxy gem/plugin detects forwarded host/uri headers and sets the session domain, default host, and relative url root. Now, any calls to url_for, named route helpers, and view url helpers will use the forwarded host/uri while still allowing you to specifically set the :host and :only_path options to override this behavior. The original session domain, default host, and relative url root are restored after each request.

The proxy gem/plugin also provides functionality to support clients that want to add CNAME or A records to their DNS instead of proxying their domain to your application. You can do something like:

# config/initializers/proxy.rb

Proxy.replace_host_with do |request|
unless request.host =~ /(\.|^)ordersapp.com$/i
"#{Account.find_by_domain(request.host).try(:subdomain)}.ordersapp.com"
end
end

This snippet of code will detect any hosts that aren't using your application's domain (which is the case for CNAME and A records) and replaces it with the account's subdomain combined with your application's host. This allows you to specify route conditions or any other logic using your application's real host and also overrides all the url generating helpers so that it still looks like the application is living on the client's domain.

Check out http://github.com/shuber/proxy for more examples.

No comments: