I'm building a multi-tenant rails application, similar to Shopify. Whenever a customer registers an Account, they will have a subdomain created at customer.myapp.com. This subdomain returns a view with data related to their account (including a /admin area).
Now in some cases, customers would like to use their own custom domain, instead of the subdomain created for them. How do I need to adjust my rails routes and controllers to return a view with data related to the customers account, based on not just the subdomain but on either the custom domain OR the subdomain?
This is how I've set up my config/routes.rb for handling subdomains:
# config/routes.rb
Rails.application.routes.draw do
...
constraints(SubdomainRequired) do
scope module: :accounts do
...
end
end
end
With app/constraints/subdomain_required.rb looking like this:
# app/constraints/subdomain_required.rb
class SubdomainRequired
def self.matches?(request)
request.subdomain.present? && request.subdomain != "www"
end
end
And finally my app/controllers/accounts/base_controller.rb setting the current account, based on the requests subdomain:
# app/controllers/accounts/base_controller.rb
module Accounts
class BaseController < ApplicationController
before_action :set_current_account
...
def set_current_account
if request.subdomain.present?
@current_account = Account.find_by(subdomain: request.subdomain)
render_404 if !@current_account
end
end
def render_404
render file: "#{Rails.root}/public/404.html", status: 404
end
...
end
end
For the DNS setup I followed the approach of companies like Shopify. It looks like they have their customers create an A record that points to the primary IP address of their app. And they have them create a CNAME for the "www" subdomain, which points to a subdomain (sites.myapp.com), set up as a CNAME for the apps subdomain (in my case managed by DigitalOcean's app platform).
IF the DNS Settings work as intended, I'm left wondering how I can point requests in the right direction when the customer lands on my app. So for example if traffic hits customer.com and it has an A record pointing to my servers primary IP, plus a CNAME for sites.myapp.com, how do I handle the request and redirect it to the correct subdomain whilst keeping the user on their custom domain?
These are the resources I've checked so far:
- Laravel application with subdomains that can be linked to other domains via CNAME
- multi tenant with custom domain on rails
- Multi-tenant dynamic multiple domains with SSL pointing to single Host/CDN
- https://answers.netlify.com/t/subdomain-and-custom-domain-based-multi-tenant-application/30482/2
- https://www.indiehackers.com/post/how-do-i-setup-a-domain-to-subdomain-architecture-like-shopify-70413820da
- https://help.shopify.com/en/manual/online-store/domains/add-a-domain/using-existing-domains/connecting-domains#set-up-your-existing-domain-to-connect-to-shopify
Thanks for your help!