Dynamic Subdomains with RubyOnRails
Following is a step by step guide to configure an application for dynamic subdomains. We are trying to set up wildcard subdomain feature similar to the one done by blogspot.com and wordpress.com.
Step 1
In advanced DNS settings of your domain, add an A record as follows
*.domain.com IN A ***.***.***.*** (server IP address)
Step 2
Modify http.conf to set up a serveralias *.domain.com for http://www.domain.com/.
Make sure you have access, or ask your service provider to do this.
Step 3
Add a wildcard entry for your domain in the Zone file for http://www.domain.com/, so that nonexistant subdomains are resolved to same public_html folder.
Now to check this, keep an index.html file in the public_html folder.
Try browsing http://www.domain.com/ and http://anything.domain.com/ . Both should resolve to the same index.html file. If this succeeds, your dynamic subdomains are set up.
To catch the subdomain in RubyOnRails modify application.rb as follows,
class ApplicationController < ActionController::Base before_filter :get_subdomain # # Other content goes here # private def get_subdomain @subdomain = request.subdomain.first @subdomain = 'www' if @subdomain.nil? end end
Now you have a subdomain catched by your application controller which can be used in all controllers.
For example, MyController makes use of @subdomain and decides what action to take. (it is a simple redirect action in this case)
class MyController < ApplicationController def index if subdomain == 'anup' redirect_to_url 'http://anup.info' else if subdomain == 'planet' redirect_to_url 'http://planetrubyonrails.com' else redirect_to_url 'http://yourdefaulturl.com' end end end
