douzhong8856 2016-10-12 11:26
浏览 101

如何在Yii2中自定义URL?

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 ?

  • 写回答

1条回答 默认 最新

  • dtlc84438 2016-10-12 13:14
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义