Hostname/Subdomain URLs and routing using ZF2
The Problem
Within wripl.com we’re using the our main domain along with a couple of subdomains, i.e api.wripl.com & oauth.wripl.com. The subdomain routing is performed using a Zend\Mvc\Router\Http\Hostname route. I was having 2 issues with this:
- My other standard routes eg ‘learn-more’ (‘/learn-more’) was available on the sub domains too. E.g. going to ‘api.wripl.com/learn-more’ would still route to my learn more page
- While on a subdomain, (be it an actual sub domain page, or a seemingly mis-routed page), the url helpers would generate the url using the current domain. E.g. I’d end up with links like oauth.wripl.com/user/register being generated
My Solution
I say my solution because there maybe a better solution that I’m not aware of.
I didn’t want to go down the route (pun intended) of custom helpers, because 3rd party modules wouldn’t work out of the box, and also the urls would still be accessible - however obfuscated.
What I did was create a ‘parent’ hostname route and added all my other pages as child routes.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
'router' => array( 'routes' => array( 'wripl-www' => array( 'type' => 'hostname', 'options' => array( //set route hostname locally ), 'child_routes' => array( 'learn-more' => array( 'type' => 'segment', 'options' => array( 'route' => '/learn-more', ... ), ), ... |
And in a *.local.php config file I set the hostname routes depending on environment :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
return array( 'router' => array( 'routes' => array( 'wripl-www' => array( 'options' => array( 'route' => 'wripl.dev', ), ) 'bgoauthprovider' => array( 'type' => 'hostname', 'options' => array( 'route' => 'oauth.wripl.dev', ), ), 'zfcuser' =>array( 'type' => 'hostname', 'options' => array( 'route' => 'wripl.dev', ), ), ), ), ); |
So now instead of $this->url(‘learn-more’) I use $this->url(‘wripl-www/learn-more’) and I always get the url with the correct hostname and the request will only get routed if the correct hostname is present, so in my example from before ‘api.wripl.com/learn-more’ now results in a 404. #win.





