简体   繁体   中英

How do I customize URL in Yii2?

我是Yii2的新用户,因此我拥有具有其类型('brand', 'author', 'company')和标头名称的Brands表,因此我需要类似www.site.com/{brand_type}/{brand_slug}的URL www.site.com/{brand_type}/{brand_slug}无控制器的名称,以便该怎么做?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM