I'm creating a multi-tenant SaaS product that is comprised of pretty basic PHP / MySQL connections. I'm using single database and mapping all tenants to a tenantId
column in the database.
I'm also using subdomains to give each tenant a front-end / back-end of the software, so upon registering, they'll be given something like company1.mysaas.dev
. Their subdomain is also mapped to their tenantId
in the database.
All tenant's domains are pointed to a single code base / the same entry point of the app, so when visiting their domain it needs to map to their config file / connect to their tenantId
in the database to load only their files.
Here's what I'm doing on my index.php
file that each subdomain is loading:
// Connect to Database
$db = new mysqli('localhost', 'root', '', 'saas');
// Check Connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$domain = $_SERVER['HTTP_HOST']; // Get current domain
$stmt = $db->prepare('SELECT `tenant_id` FROM `domains` WHERE domain = ?');
$stmt->bind_param('s', $domain);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$tenantId = $row['tenant_id']; // Get Tenant ID based on current domain
if ($tenantId) {
$serverConfig = "tenants/$tenantId/config.php";
if (file_exists($serverConfig)){
return require($serverConfig);
} else {
header("Location: https://mysaas.dev"); // No config file found, redirect back to app homepage
}
} else {
header("Location: https://mysaas.dev"); // No tenant ID found, redirect back to app homepage
}
For the most part, the above is working as I test just a hand full of subdomains.
My question is if this is a proper way of handling incoming requests based on subdomains or is there a more efficient way when scaling this up?
What if there's a thousand people hitting the entry point of the app all from different tenant's subdomains, will this scale?