Jeemusu
Jeemusu

Reputation: 10533

Add A 301 Redirect to Codeigniter .htaccess

I've been trying to set up a redirect for a page that recently moved. The page was originally at http://example.com/foo/, but has since moved to http://example.com/foo/bar/ .

I tried the following rule in my sites .htaccess file:

RedirectMatch 301 ^/foo/$ /foo/bar/

However going to the url http://example.com/foo/ resulted in a redirect to the url http://example.com/foo/bar/?/foo/. While the url works and the page I want to redirect to loads, I would quite like to get rid of the extra ?/foo/ at the end of the url.

Here is my full .htaccess:

RewriteEngine On
RewriteBase /

# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [R=301,L]

# allow access to certain directories in webroot
RewriteCond $1 !^(index\.php|robots\.txt|css/|lib/|js/|images/|^(.*)/images)

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

# page redirects
RedirectMatch 301 ^/foo/$ /foo/bar/

Upvotes: 0

Views: 5067

Answers (2)

Jeemusu
Jeemusu

Reputation: 10533

Adding a RewriteRrule to the top of the .htaccess after the RewriteBase / file solved the problem.

RewriteRule ^foo/$ /foo/bar [R=301,L]

Upvotes: 5

I found it easier to redirect from controller instead of .htaccess because .htaccess was adding a querystring at the end.

For example I've put this in my controller's action:

if ($this->uri->segment(2)==='old_url') {
  redirect(base_url() . $this->lang->lang() .'/new-url', 'location', 301);
}

Upvotes: 0

Related Questions