Configure different routes in Rails depending on the domain/host name
We can have a Rails application with different domains/hostnames, and responding different to each.
First of all we need to configure our localhost to have different hostnames. In /etc/hosts add:
127.0.0.1 www.localhost.uk.local
127.0.0.1 www.localhost.jp.local
Now in the application to start the server for that hosts without port (port 80), we’ll need to stop the current server in port 80 and start it with the root user:
sudo apachectl stop
sudo script/server -p 80
Then we need to monkey patch the default Rails routing.
Add to the end of config/environments.rb
Create lib/core_ext.rb
Create lib/core_ext/routes.rb
I based that code on this post http://www.smallroomsoftware.com/articles/2007/2/10/rails-routing-based-on-hostname.
Now in the routes we can use hostname as condition:
Obviously we can set up it differently depending on the environment. You can use this technic.
If we use page caching, we’ll need to store it in different folders depending on the hostname, otherwise if the domains have the same URI, will get the same cached page. In the controler/s:
restart the server.
There is another way to do it with the request routing plugin http://agilewebdevelopment.com/plugins/request_routing:
Install the plugin:
script/plugin install http://svn.danwebb.net/external/rails/plugins/request_routing/trunk/
In my case, I was using multiple TDLs domains, so I added the hostname option to the plugin. Looks like this:












