Cakephp | URL routing using prefix before domain name

|
| By Webner

Routes in an application are configured in app/Config/routes.php. Defining your own routes allows you to define where your application will take the control to for a given URL.

Default routing is like this:

domain/controller/action
Ex. www.xyz.com/user/login
Prefix routing will add a prefix (aryan below) before the domain name :
Prefix routing: prefix.domain/controller/action
Ex. aryan.xyz.com/user/login

For achieving prefix routing put following code lines in your app/Config/routes.php file:

preg_match('/^(?:www.)?(?:(.+).)?(.+..+)$/i', env('HTTP_HOST'), $matches);
if(empty($matches[1]))
$SUBDOMAIN = false;
else
$SUBDOMAIN = $matches[1];
$HOST = $matches[2];
$BASE_URL = 'http://'.$SUBDOMAIN.'.'.$HOST.'/';
$subdomain = substr( env("HTTP_HOST"), 0, strpos(env("HTTP_HOST"), ".") );
if (isset($matches[1]) && $matches[1]!='')
{
 $url = array_filter(explode("/", Router::url()));
 $trail = $url;
 // write your own code here as needed
 if(strtolower($trail[1]) == 'envisiontel')
 Router::redirect('/*', 'http://'.$matches[1].'.xyz.com’);
...
}
CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *