Complete URL management for a Web application involves two aspects:
- When a user request comes in terms of a URL, the application needs to parse it into understandable parameters.
- The application needs to provide a way of creating URLs so that the created URLs can be understood by the application.
For a Yii application, these are accomplished with the help of CUrlManager.
Yii is one of favourite php framework of all time. Here we give another one hidden secret of Yii which is very helpful for changing the URL structure to your application for more convenient reading.
Creating URLs
Although URLs can be hardcoded in controller views, it is often more flexible to create them dynamically:
$url=$this->createUrl($route,$params);
where $this
refers to the controller instance; $route
specifies the route of the request; and $params
is a list of GET
parameters to be appended to the URL.
By default, URLs created by createUrl is in the so-called get
format. For example, given $route='post/read'
and $params=array('id'=>100)
, we would obtain the following URL:
/index.php?r=post/read&id=100
where parameters appear in the query string as a list of Name=Value
concatenated with the ampersand characters, and the r
parameter specifies the request route. This URL format is not very user-friendly because it requires several non-word characters.
To remove index.php
To remove index.php from the url you must add the .htaccess
file in your root.
RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php
After adding .htaccess go to protected/config/main.php
file add showScriptName=>false.
'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( '<controller:w+>/<id:d+>'=>'/view', '<controller:w+>/<action:w+>/<id:d+>'=>'/', '<controller:w+>/<action:w+>'=>'/', ), ),
To hide index.php
To hide "index.php" from the url on a website, add an .htaccess file to your web root, with this text:
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
and in /protected/config/main.php, set:
‘urlManager’=>array(
‘urlFormat’=>’path’,
‘showScriptName’=>false,
‘caseSensitive’=>false,