So, I have several subdomains for my project with mezzio framework (zend expressive):
- example.com
- journal.example.com
- account.example.com
How can I use it in routes?
This example does not work:
$app->get('journal.example.com', Journal\Handler\HomePageHandler::class, 'journal.home');
Disclaimer
This answer provides a solution to the question of routing requests to subdomains to a specific RequestHandler. However, is not a good practice, since it introduces difficulties like the overhead in routes configuration and maintaining two routes configurations. In addition, it does not solve the subdomain-specific path routing (e.g. http://journal.example.com/new or http://journal.example.com/list).
Using the same application across various subdomains can mean challenges in session handling and so forth. Using the same domain for one application makes these issues obsolete.
Possible solution
Since routes are not aware of the host, a plain solution in the routes configuration is not possible. It can be achieved by using a routing middleware.
Subdomain routes configuration
Define routes in
config/autoload/subdomain-routes.global.phpRouting middleware
The routing middleware uses a SuperFactory
src/App/Service/SuperFactory.phpto retrieve the services from the container.The routing middleware
src/App/Middleware/SubdomainRouter.phpreturns the response of the RequestHandler, if a matching subdomain is found.Pipeline
The routing middleware must be placed in the pipeline before
Mezzio\Router\Middleware\RouteMiddleware.Finish
Now requests to http://mezzio-subdomains.localhost/, http://account.mezzio-subdomains.localhost/ and http://journal.mezzio-subdomains.localhost/ are routed as configured.