简体   繁体   中英

How to make right url address in Yii2

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM