Our product is in production and we decided to have a new subdomain which will target a different set of Users. The end goal is to have the same Code base but render different CSS based on subdomain.
Since our App is hosted on Heroku, the first thing I do is checked feasibility of two DNS pointing to same app, I raised the below ticket on heroku:
https://help.heroku.com/sharing/af2a96f9-1559-45c4-9459-db805fe29229
Heroku Confirmed that it is quite easy to do, so now we move ahead with the development.
Here the first problem is to get two URL pointing to our same App in local.
We all know and use below URL in local:
We need another URL as below:
http://MBEportal.localhost:3000
You can achieve this with below steps:
1 – Login as admin user on terminal:
sudo su –
2 – Edit /etc/hosts file
nano /etc/hosts
The above command will open /etc/hosts file for you in terminal.
You will find few lines there, the important one is:
127.0.0.1 localhost
This is the line which basically map localhost to IP 127.0.0.1
Add a new line below it:
127.0.0.1 MBEportal.localhost
This is telling that the new DNS MBEportal.localhost should also map to IP 127.0.0.1
press cntr + x to exist editing
It will ask you to save before existing. Press Y to save the change.
3 -restart your rails server.
Now you can access your localhost at both the below URL
http://MBEportal.localhost:3000
4 – Parse Subdomain in Controller
So, at this point we have simulated subdomain behavior. Also both hitting same code base as expected.
But still when I go to controller action and try to see subdomain, it return empty array
request.subdomains -> []
It look like our server treating http://MBEportal.localhost as a single domain.
This can be fixed by adding below line in environment/development.rb file
config.action_dispatch.tld_length = 0
Restart your server again and this time you will get the subdomain from URL
request.subdomains -> [“mbeportal”]
great ! now we can find the subdomain from request object and thus execute different logic or layout or any other thing specific to the particular domain.
Some other detail which you can read from request object are:
request.base_url -> http://MBEportal.localhost:3000
request.host -> mbeportal.localhost
request.domain -> localhost
November 15, 2020 at 5:51 pm
Thanks, very useful