Redirect 301 in htaccess Codeigniter

Viewed 221

How to do 301 redirects in CI? I am creating a new website in CI and I would like to do 301 redirects from the earlier version of the website, where the URL structure looks a bit different, so I wanted to redirect the most important subpages in htaccess, but the regular rules in htaccess do not work for me, I think because of entries in routes.php

$route['(:any)/(:any)/(:num)'] = 'ads/cat/$1/$2/$3';
$route['(:any)/(:any)'] = 'ads/cat/$1/$2';
$route['(:any)'] = 'ads/cat/$1';

and my htaccess file

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

and I would like to redirect for example

RewriteRule ^oldcat1/oldcat2/oldcat3/ http://localhost/newcat1/newcat2 [R=301,L]

But this redirect doesnt work. How to deal with this?

1 Answers

You need to make sure you place your external redirects before the existing directives that send the request to your CodeIgniter front-controller, otherwise, they simply won't be processed.

For example:

# External redirects
RewriteRule ^oldcat1/oldcat2/oldcat3/ http://localhost/newcat1/newcat2 [R=301,L]

# Front-controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

This doesn't have anything to do with routes you might have defined in CodeIgniter since .htaccess is processed before routes.php is called.

Related