custom url in codeigniter

2019-08-30 23:03发布

问题:

I have controller called 'project' with method of index

I want to pass project_id it works with this url: URL: http://example.com/project/index/project_id

what I am trying to do is to have url for each project http://example.com/project_id for example: http://example.com/rickyboby

I tried this code $route['(:any)'] = "project/index/$1"; It worked I could access project_id from url www.example.com/project_id but the problem is I have other controllers are not working now, for example I have welcome controller, the url: www.example.com/welcome/ is routing me to project page, how can I solve that ?

回答1:

You need to whitelist all the controllers you have before the "any" rule because they go in order (so in your example, /welcome would take you to project/index/welcome). For example:

$route['welcome'] = "welcome";
$route['somethingElse'] = "someOtherUrl";
$route['(:any)'] = "project/index/$1";

You can also try to think of a clever way of doing this with regex, but I think you're better off with a whitelist.


This is a basic programming concept and probably doesn't belong here, but you can always do something like:

$controllers = array('welcome', 'otherController', 'etc');
foreach($controllers as $c) {
    $route[$c] = $c; // make all URLs from the list go to their same-named controllers
}
$route['(:any)'] = "project/index/$1"; // handle the other URLs

One more thing - don't forget to prevent users from giving projects names that match existing controller names (such as welcome) because their project won't be accessible! There, yet another reason to have that controller list someplace...



回答2:

Place the "welcome" routing rule before the "project" routing rule. This way the system will match welcome and won't go looking for the next rule. Alternatively, you could use (:num) instead of (:any), this way it will match only numbers (in case your project ids are numbers).