codeigniter default controller url routing

2019-02-15 16:53发布

I am putting together a simple networking site and would like to have the urls work similar to facebook so by typing in domain.com/username I would get a user profile. I can do this already this way

Logged in users profile at

domain.com/

other users profile at

domain.com/home/username

The default controller is called home and I am currently using the _remap function to check for extra url parameters to display different data based on what is or isn't passed.

My question is how would I map this out so I can access user profiles by:

domain.com/username 

Is there a routes.php setting I could use? htaccess?

3条回答
Summer. ? 凉城
2楼-- · 2019-02-15 17:17

you should add the following rule in your config/routes.php

// Profile Route
$route['(:any)'] = 'home/$1';

this will reroute all your request to the home controller.

so domain/michelle will re be rerouted as domain/home/michelle but in this case all your requests will be rerouted to the home controller eg. domain/pages/about will also be rerouted to domain/home/pages/about wich false.

domain/michelle => domain/home/michelle // TRUE
domain/pages/about => domain/home/pages/about // FALSE

so you MUST add for each request a identic rule before the Profile Route, eg. $route['pages/(:any)'] = 'pages/$1';

put it all together :

// Page Route 
$route['pages/(:any)']  = 'pages/$1'

// Last Profile Route
$route['(:any)'] = 'home/$1';
查看更多
叛逆
3楼-- · 2019-02-15 17:21

This is not the easiest thing to do in Codeigniter. To do so you need first you need to define all the routes you use in routes.php and to the end of file you need to add line, that will send all other requests to your controller that will check if user exists.

$route['stores/(:any)'] = 'stores/$1';
$route['pages/(:any)'] = 'pages/$1'; 

$route['(:any)'] = "home/$1"; //this route will return user's page
查看更多
闹够了就滚
4楼-- · 2019-02-15 17:31

You can do this by modifying the routes.php file available in application/config file. To learn more about routes.php. Here is the link URI routing in Codeigniter

查看更多
登录 后发表回答