Subdomains control for url in slim

Hi there,

I would like to create multiple sudbomain eg:
foo.mydomain.com
bar.mydomain.com

these subdomains will be dynamic and I would like to have different controllers based on the subdomain and load from a single twig file

I am still new to the slim framework so apollogies for the noob question

There is not any built-in support for parsing subdomains. However, here’s how I would do this. I would configure the default Nginx virtual host to answer for these subdomains. The virtual host will direct all PHP requests to the appropriate Slim bootstrap file. You can write a simple Slim middleware that parses the request subdomain so you can take the necessary actions in your route callbacks. Does this make sense?

1 Like

Maybe switching to https://route.thephpleague.com/4.x/routes/ for routing could help too? It’s inspired by fastroute, so could be close enough and slim4 decoupled the router completely afaik. Anyone tried this?

$app->get('/myendpoint', function (Request $request, Response $response) { // Get full host (e.g., sub.example.com) // Get the Referer header $referer = $request->getHeaderLine('Referer'); $refererHost = null; $subdomain = null; if (!empty($referer)) { $parts = parse_url($referer); if (isset($parts['host'])) { $refererHost = $parts['host']; // e.g. store.mycompany.com // Split by dots $hostParts = explode('.', $refererHost); if (count($hostParts) > 2) { // assumes domain like sub.example.com (3+ parts) $subdomain = $hostParts[0]; } else { $subdomain = null; // no subdomain (just example.com) } } } error_log($subdomain);