Add a 'prefix' controller to url in CodeIg

2019-09-16 18:12发布

问题:

I currently have an api running on CodeIgniter which can be accessed via http://mysite.com/controller/method/variable. However, I want to convert the url, adding an 'api' prefix before the controller, leaving the url to look like http://mysite.com/api/controller/method/variable.

I presumed that this is to do with routing, so I added two new routes to the routes.php file:

$route['api/users/auth'] = 'users/auth';
$route['api/users/create'] = 'users/create';

This now adds the 'api' prefix to following urls.

http://mysite.com/api/users/auth
http://mysite.com/api/users/create

But now, the endpoints can still be accessed via a call to the above urls without the 'api' prefix.

How can I prevent this from happening or what would the best way to do this be?

回答1:

A solution should be to remove the method auth and create from your Users controller and put them into a new controller named Users in application/controllers/api/users.php. Then you can also remove the specific route for your api, it will work. (see here)