How to create dynamic subdomain rails

How can I create a subdomain for each user who registers on my site? For example, userone.mysite.com and usertwo.mysite.com.

In php, this can be done using the apache virtual host, but I cannot figure out how to do the same in Ruby on Rails. Here's how to do it in apache

<VirtualHost *:80> ServerName www.mysite.com ServerAlias mysite.com *.mysite.com DocumentRoot /www/domain </VirtualHost> 

I went through many blogs, but could not find a solution. Please advice.

+5
source share
2 answers
  <VirtualHost *:80> ServerName mysite.com ServerAlias *.my_site.com # !!! Be sure to point DocumentRoot to 'public'! DocumentRoot /var/www/html/my_site <Directory /var/www/html/my_site> # This relaxes Apache security settings. AllowOverride all # MultiViews must be turned off. Options -MultiViews # Uncomment this if you're on Apache >= 2.4: Require all granted </Directory> </VirtualHost> 

and do not forget about changing the name cname * in your domain in DNS

+1
source

Addition to the Dinesh Saini answer - you also need to update your Rails configuration accordingly. For example, if you need deep subdomains, you should change config.action_dispatch.tld_length to staging.rb, and you should double-check route.rb.

Live example: I had to implement store display by subdomain - example URL my-shop.shop.testapp.com. So what I did, except for server configuration changes

  constraints (lambda { |req| req.subdomains[1] == 'shop' }) do get '/', to: 'shopes#show', as: :shop end 

In the controller to search for a resource

  Shop.find_by(id: request.subdomains[0]) 

I also installed

  config.action_dispatch.tld_length = 2 

I did this to create env because it has such a staging.testapp.com url, so I need a different subdomain level. I think for you it is only good to check that it has 1.

0
source

Source: https://habr.com/ru/post/1238099/


All Articles