Using subdomains like parameter for nice looking personal URL-s, while keeping the www subdomain

Using the Zend_Controller_Router_Route_Hostname we can make nice looking personalized URL addresses like
http://username.example.com (http://john.example.com)

Lets say we have ‘userpage’ controller with ‘view’ action and want john.example.com to route to this userpage ‘controller’ and this th ‘view’ action, setting a parameter ‘username’ to ‘john’. This is easy:


$pathRoute = new Zend_Controller_Router_Route('*');

$userpageRoute = new Zend_Controller_Router_Route_Hostname(':username.example.com',
array('controller'=>'userpage', 'action'=>'view'));
$router->addRoute('userpage', $userpageRoute->chain($pathRoute));

what is to chain the Hostname route with standart Zend_Controller_Router_Route(’*') route, so we can use parameters:
http://john.example.com/param1/val1/param2/val2
this will open the ‘userpage’ controller, ‘view’ action with the following parameters:
‘username’ => ‘john’,
‘param1′ => ‘val1′,
‘param2′ => ‘val2′

But what happens when someone types in the address bar “www.example.com”? Our hostname route will match and ‘userpage’ controller with ‘view’ action will be opened with ‘username’ set to ‘www’. Most of the times this is not what we want. So we want to exclude ‘www’ subdomain somehow. Furtunately the Zend_Controller_Router_Route_Hostname constructor have third parameter, $reqs, which we can use to set requirements for the variables of the route. We have one variable - ‘username’, and want it not to match the literal ‘www’ value. So we have to write regular expression with the meaning “do not match ‘www’”. This is not so common task, and to accomplish it we will use “negative lookahead”:
^(?!www$).*$
what this means is: after the start of the string, make sure the literal ‘www$’ (www, followed by end of string) cannot be matched, then match anything else.

The match method of Zend_Controller_Router_Route_Hostname class adds the start of string and end of string anchors (^ and $), so we write the regular expression omiting these:


$pathRoute = new Zend_Controller_Router_Route('*');

$userpageRoute = new Zend_Controller_Router_Route_Hostname(':username.example.com',
array('controller'=>'userpage', 'action'=>'view'),
array('username'=>'(?!www$).*'));
$router->addRoute('userpage', $userpageRoute->chain($pathRoute));

and we are done :)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Fark
  • Furl
  • Live
  • Ma.gnolia
  • Reddit
  • Spurl
  • Technorati