Alexander Zeitler

Alexander Zeitler

Dynamic subdomain per tenant using nginx and Docker

Published on Wednesday, January 11, 2023

Photo by José Martín Ramírez Carrasco on Unsplash

Even if you don't use B2B SaaS, you might have seen urls like https://theleaddeveloper.slack.com, where you can have your own subdomain on slack.com for your Slack channel.

While playing around with some nginx settings, I noticed that this could actually be used for dynamic subdomains per tenant.

Long story short, here's the solution (which can certainly be optimized):

# sample shows only relevant part of the config, the rest is omitted for the sake of brevity

server {
    listen 443 ssl;

    server_name *.tempuri.org;

     location / { 
        set $tenant ""; 
  
        if ($host ~* "^(.+)\.tempuri.org$") {
          set $tenant $1; 
        }

        resolver 127.0.0.11;
        proxy_pass http://app/tenant?slug=$tenant;
      }   
}

So what's going on there?

Given our domain is tempuri.org, we want tenants to be available via tenantname.tempuri.org, hence our nginx server is listening on *.tempuri.org.

Next we're using a little regular expression to pick up the name of the subdomain (which equals our tenant name/slug) the user entered.

After that we set the DNS resolver to 127.0.0.11 (yes: eleven) which is the internal Docker DNS resolver. That's required to make sure the host name app used for the proxy_pass directive can be resolved. app is the name of the container hosting the actual application which e.g. shows a branded login screen or third party identity providers per tenant.

What are your thoughts about "Dynamic subdomain per tenant using nginx and Docker"?
Drop me a line - I'm looking forward to your feedback! email
Imprint | Privacy