Codeigniter .htaccess redirection for query string URL

Recently EduSagar was upgraded to accommodate MVC framework provided by Codeignitor. This was done in an effort to get more meaningful and SEO-friendly segmented URLs. Things worked pretty well, but then we faced a weird issue. Google search was still displaying old URLs which was resulting in 404 error page. This was when we decided to redirect all such URLs to the newer and valid ones. Redirection with code 301 will show "moved permanently" as HTTP response to the search engines so that they can use that extra information to quantify search results better.

A single URL redirect is as simple as adding the following line in your .htaccess file (only if mod_alias module is installed on your Apache server):

<ifmodule mod_alias.c>
# Redirect 301 old_url new_url
Redirect 301 "/modules/quiz/quiz_main.php"

Another simple way of specifying the redirection would be to add a route in application/config/routes.php file. You need to provide the name of controller and the method for the URL you want the redirection to happen.

$route["modules/quiz/quiz_main\.php"] = "quiz";

However, the same doesn't work well with the query based string URLs. Following redirect statements containing query strings are simply ignored as they are not valid.

Redirect 301 "/articles/view_article.php?id=1"
Redirect 301 "/articles/view_article.php?id=2"

To get it working, we need to rewrite the URL instead of redirecting it. For this we need 'mod_rewrite' module to be installed on your Apache server.

<ifmodule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/articles/view_article\.php$
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^(.*) [R=301,L]

"RewriteEngine On" enables the URL rewrite capability. RewriteCond are the conditions which must be true, to get the URL rewrite triggered. Here we check if the URL contains "/articles/view_article.php" and the query string is "id=<some integer>", our RewriteRule will be called. The rewrite rule will change the matched pattern (whole URL in this case) to the one we want - "<some integer>". The "%1" maps to the integer that matched the pattern in the RewriteCond for query string, i.e. ^id=([0-9]*)$.

"R=301" states that the server will return 301 response code to the browser and search engines. Along with this 'L' here specifies that this will be the last rule to execute if all the RewriteCond matched properly.

Once you are done with this, "/articles/view_article.php?id=1" will be successfully redirected to "".

Is something missing? By default, the original query string gets passed on to the rewritten URL. To discard the original query string append a '?' at the end of the URL in the rule.

RewriteRule ^(.*) [R=301,L]

Hope that gets you get going...
comments powered by Disqus