Reputation: 63
I trying to enable pretty url in yii2 but it doesn't work as needed.
urlManager configuration:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => '/',
]
public function actionIndex($custom_param)
{
print($custom_param);
}
example.com/mycontroller?custom_param=value
works perfectly. But I need URLs such as example.com/mycontroller/value
.
Upvotes: 1
Views: 2509
Reputation: 1692
In your web.php file below Components use this code:
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
Create A .htaccess file in your web folder and paste it:
RewriteEngine on # If a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # therwise forward it to index.phpRewriteRule . index.php
Upvotes: 1
Reputation: 33548
If you want to apply this toindex
action of mycontroller
and in case of custom_param
is integer, add this to rules
section of urlManager
:
`urlManager' => [
'rules' => [
'mycontroller/<custom_param:\d+>' => 'mycontroller/index',
],
],
Otherwise you can modify pattern to fit your needs.
For example if custom_param
is string, change d+
to w+
.
If you want to apply this rule to other controllers, you can do it like this:
'<controller:(mycontroller|anothercontroller)>/<custom_param:\d+> => '<controller>/index'
,
Read more in official documentation:
Upvotes: 4