Codeigniter URL redirection and routing

2020-07-24 05:14发布

问题:

I am trying to redirect URL's with Codeighiter routing. I could not write routing for the following.

If the URL comes with /api/some/some I want to redirect it to api/some/some, otherwise I want to redirect the URL to /home/index.

i.e if any URL starts with api/ i don't want to change that URL other wise i want to redirect it to default controller home/index

What i tried is mapping the codeigniter URL routing.

$route['api/(:any)'] = 'api/(:any)';

$route['(:any)'] = 'home/index/';

I am trying with codeigniter URL routing technique but i am not able to achieve this.

Is this is the way to redirect URL's at codeigniter level with out touching server side redirection or is there any better approach to do this?

回答1:

Solution 1. Using CodeIgniter routing

try this in your application/config/routes.php

$route ['api/(:any)'] = "api/$1";
$route ['(:any)'] = "home/index/$1";
$route ['default_controller'] = "home";
  1. For any matching () in patter, you'l need to add respective $1 or $2, $3.. based on position of that () patter. i.e for first () its $1, for second () its $2 and so on.

  2. You'l need to set your default controller to home.

Solution 2. Using .htaccess page redirection

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/api(.*)$ 
RewriteCond %{REQUEST_URI} !^/home/index$ 
RewriteRule ^.*$ /home/index [R=301,QSA,L]