1

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.

2 Answers 2

4

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:

Sign up to request clarification or add additional context in comments.

1 Comment

What is if the custom param has a specific value? i,e controller/action/1 to be controller/action/ In other words removing the param value if it has specific value. It is very important in pagination and SEO
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.