douzao2590 2017-03-14 08:10
浏览 77
已采纳

如何在Yii2中创建正确的URL地址

I need to do an url address that looks like website/user/username where username is coming from database. I've tried to reach it by placing a $user variable in my action function as a parameter and result looks like this website/action?user=username. But it looks kind of hinty and ugly. How can I get a desirable result?

  • 写回答

1条回答 默认 最新

  • dongre6227 2017-03-14 08:45
    关注

    First you need to configure url rules in config/web.php.

    [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' => [
                "user/<username:\w+>"=> "controller/action"
            ],
        ],
    ],
    

    ]

    And add url match condition in rules array like "user/<username:\w+>"=> "controller/action"

    Create. htaccess file with below url condition in web folder

    RewriteEngine on
    # If a directory or a file exists, use it directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # Otherwise forward it to index.php
    RewriteRule . index.php
    

    And generate urls with Url helper class or Html class like below

    echo Url::to(['controller/action', 'username' => 'jack']);
    
    Or 
    
    echo Html::a('Profile', ['controller/action', 'username' => 'jack'], ['class' => 'profile-link']) 
    

    Note:- controller name, action name and username should match with Url condition. Which we define in rules array.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部