问题
I wold like to create this kind of URL for my users when they register a username mysite.com/username
I've search many posts on this site and I see people doing it like this mysite.com/user/username
I would like to get rid of the user and just have it go directly to mysite.com/username
What would be the best way to this?
回答1:
I am not familiar with CodeIgniter but here is a general answer for why people don't use mysite.com/username:
mysite.com/user/username is a good solution because usually the URL dispatcher passes username to a function/module that handles users' page.
mysite.com/username is a bad solution because your dispatcher will have to have a greedy rule after all your other rules, to pass everything other that those previous rules to the module/function that handles users' page.
Now suppose you want to use mysite.com/username and suppose you have mysite.com/logout which lands users to the logout page. A user comes and registers himself with "logout" as his username. Then how are you going to say by accessing mysite.com/logout Mr. logout wants to logout or wants to see his page?
回答2:
You could look into routes:
http://codeigniter.com/user_guide/general/routing.html
You enter routes into config/routes.php
As an example:
$route['([a-zA-Z]+)'] = "main_controller/user_function/$1";
But as @Nylon Smile said above, if you attempt to use logout, it will try to access logouts' user page.
回答3:
You can do this by adding an item to the $route array in 'config/routes.php':
$route['([a-zA-Z0-9_-]+)'] = "user/index/$1";
This maps example.com/whatever to to the 'index' function of the 'user' controller.
Yes, there will be collisions if you have a 'logout' controller and a user named 'logout'. You can solve this by putting adding the following item to the $route array before the one above:
$route['logout'] = "logout";
And keeping a blacklist of usernames that includes your controllers. This will take some upkeep, so you may want to go with the other solutions listed here that prefix something like 'user/' in the URL before their username and avoid all that.
来源:https://stackoverflow.com/questions/4632857/codeigniter-i-would-like-create-user-urls-for-my-users-when-they-create-a-user