如何在Yii2中自定义URL?

时间:2016-10-12 11:26:53

标签: php yii2

我是Yii2中的新手所以我有他们的类型- debug: var: dbtables_data 和他们的slug名称的Brands表所以我需要像- debug: msg="{{item}}" with_items: "{{ dbtables_data.stdout_lines | default([]) }}" 这样没有控制器名称的URL所以如何做到这一点?

1 个答案:

答案 0 :(得分:0)

这通常称为漂亮网址。要在Yii2中实现这一点,请将其放在'components'密钥

下的应用配置文件中
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        // ...
        '<type:\w+>/slug:\w+>' => 'yourcontroller/youraction',
        // ...
    ],
],

结果是,当您以指定的格式传递URL时,您的控制器将$type$slug作为您可以在控制器中使用的参数,预期采用以下格式:

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

请注意,即使网址不在网址中,您也需要配置网络服务器来执行应用index.php。对于Apache,可以使用.httaccess (More details here)

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

The Definitive Guide to Yii 2.0有关于此主题的优秀部分