如何在 Yii2 中自定义 URL? [英] How do I customize URL in Yii2?

查看:36
本文介绍了如何在 Yii2 中自定义 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Yii2 的新手,所以我有 Brands 表,其中包含它们的类型 ('brand', 'author', 'company') 和它们的 slug 名称,所以我需要这样的 URL www.site.com/{brand_type}/{brand_slug} 没有控制器名称那么怎么做?

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 ?

推荐答案

这通常称为漂亮的 URL.要在 Yii2 中实现这一点,请将其放在 'components'

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',
        // ...
    ],
],

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

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
    }
    ...
}

请注意,您将需要您的网络服务器配置执行您的应用程序的 index.php,即使它不在 URL 中.对于 Apache,这可以完成,例如,使用 .httaccess (此处有更多详细信息) :

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

Yii 2.0 权威指南 有一个关于这个主题的精彩部分

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

这篇关于如何在 Yii2 中自定义 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆