简体   繁体   English

如何在Yii2中自定义URL?

[英]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 要在Yii2中做到这一点,请将其放在'components'键下'components'应用程序配置文件中

'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: 结果是,当您以指定的格式传递URL时,控制器将$type$slug作为您可以在控制器中使用的参数,其形式应为:

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. 请注意,您将需要Web服务器配置执行应用程序的index.php即使它不在URL中也是如此。 For Apache this can be done, for example, using .httaccess (More details here) : 对于Apache,例如,可以使用.httaccess来完成(更多详细信息在这里)

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 《 Yii 2.0权威指南》中有一个非常出色的章节,关于此主题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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