douzao2590
2017-03-14 16: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?

图片转代码服务由CSDN问答提供 功能建议

我需要做一个看起来像 website / user / username 的网址< em> username 来自数据库。 我试图通过在我的动作函数中放置一个$ user变量作为参数来达到它,结果看起来像 website / action?user = username 。 但它看起来有点简洁和丑陋。 我怎样才能得到理想的结果?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongre6227 2017-03-14 16: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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题