I am making a multi-tenant platform. I have my main url as example.com and every new user will get a subdomain with username.example.com this is working. It is running on an Ubuntu droplet on Digital ocean.
I want to go one step further and allow them to add custom domains which point to my app by creating a an A name record on their DNS. I got this working as well by setting things up manually and writing additional server block for custom domain. I started with certbot for generating the certificates but then modified a lot of code manually.
Here is what my nginx file look like at /nginx/sites-available/example.com:
server {
server_name example.com *.example.com;
# pass to NODEJS app running at :3000
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
listen [::]:443 ssl ipv6only=on;
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com-0001/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com-0001/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
server_name customdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/customdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/customdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
listen 80;
listen [::]:80;
server_name ~^(?<subdomain>.+)\.example.com$;
return 301 https://$subdomain.example.com$request_uri;
}
server {
listen 80;
listen [::]:80;
server_name customdomain.com$;
return 301 https://customdomain$request_uri;
}
So My questions are :
Is there a way I can do this automatically - getting the certificate for custom domain on the fly and allowing it to go to my nodejs app?
Should I be creating multiple files under
available-domainsinstead of multiple server blocks in same file ?- Should I just make it under default instead?
see that the location block is repeating in every server block, is it possible to do this in a more DRY approach ?
I am very new to all this, so if there is a better way to do the multi-tenant setup with SSL and custom domains ?
thank you.