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.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报