Changing pattern of url to accept username like facebook

江枫思渺然 提交于 2019-12-23 05:20:03

问题


I need to covert user profile link from this http://example.com/site/index?user_id=sami.yaqoub

To be like Facebook http://example.com/sami.yaqoub

I changed the rules of config file to except that.

Config.php

<?php
..
 'urlManager' => array(
            'urlFormat' => 'path',
            'showScriptName' => false,
            'rules' => array(
                    '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                '<user:[a-zA-Z0-9_-]\w+>'=>'site/index',// here is the code 
            ),
        ),
...
?>

It worked with all words not contained any dot "." , so I changed it to be like this

 '<user:[a-zA-Z0-9_-.]\w+>'=>'site/index',// return error

But also not worked . What is the best method in this case to except this formula Name.anything

Thanks in advance


回答1:


In you regexp [a-zA-Z0-9_-.]\w+ you can match things like .helloworld but not hello.world because you match the dot . character only in first position.

You should write it like that : [a-zA-Z0-9_-.][\w.]+.

I am not sure, but maybe Facebook does not allow special characters in first position such as dot or dash.-. In that case the correct answer would be : [a-zA-Z0-9][\w.]+ or shorter \w[\w.]+

Note that \w in a regexp matches word characters. \w is equivalent to [A-Za-z0-9_]




回答2:


Try create a .htaccess file in root folder and paste this code below.

# if you have mod rewrite installed in your hosting space, you can enable pretty url for
# compressed css/js by uncommenting following lines

#RewriteEngine On
#Options FollowSymLinks
#RewriteRule   ^packs/(\w+)\.(css|js)   packs/jscsscomp.php?q=$1.$2 

Options +FollowSymlinks
Options -Indexes

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L,QSA]

<Files .htaccess>
order allow,deny
deny from all

This might help also-> Yii how to get clean and pretty URL




回答3:


I believe what you want to do is create a Slug.

Take a look here if you want to create it yourself or check any already made plugins that do it for you.



来源:https://stackoverflow.com/questions/30705325/changing-pattern-of-url-to-accept-username-like-facebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!