How do I customize URL in Yii2?

2019-09-03 16:06发布

I'm new in Yii2 so I have Brands table with their types ('brand', 'author', 'company') and their slug name so I need the URL like that www.site.com/{brand_type}/{brand_slug} without controller name so how to do that ?

标签: php yii2
1条回答
祖国的老花朵
2楼-- · 2019-09-03 17:08

This is commonly called pretty URLs. To do achieve that in Yii2 put this in your app config file under 'components' key

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        // ...
        '<type:\w+>/slug:\w+>' => 'yourcontroller/youraction',
        // ...
    ],
],

The result is that when you passed a URL in the format you specified, your controller will $type and $slug as parameters you can use in your controller which is expected to take the form:

class YourcontrollerController extends YourBaseController
{
    ...
    public function actionYouraction($type, $slug)
    {
        // Do whatever you want with these variables
    }
    ...
}

Notice that you will need your web server to configure executing your app's index.php even if it is not in the URL. For Apache this can be done, for example, using .httaccess (More details here) :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

The Definitive Guide to Yii 2.0 has an excellent section about this topic

查看更多
登录 后发表回答