Hostname/Subdomain URLs and routing using ZF2


The Problem

Within we’re using the our main domain along with a couple of subdomains, i.e & The subdomain routing is performed using a Zend\Mvc\Router\Http\Hostname route. I was having 2 issues with this:

  1. My other standard routes eg ‘learn-more’ (‘/learn-more’) was available on the sub domains too. E.g. going to ‘’ would still route to my learn more page :(
  2. 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 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.

And in a *.local.php config file I set the hostname routes depending on environment :

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 ‘’ now results in a 404. #win.