簡體   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}無控制器的名稱,以便該怎么做?

這通常稱為漂亮網址。 要在Yii2中做到這一點,請將其放在'components'鍵下'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
    }
    ...
}

請注意,您將需要Web服務器配置執行應用程序的index.php即使它不在URL中也是如此。 對於Apache,例如,可以使用.httaccess來完成(更多詳細信息在這里)

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

《 Yii 2.0權威指南》中有一個非常出色的章節,關於此主題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM