views:

154

answers:

2

I have a basic CMS in PHP/MySQL where content managers can create pages to the system for public viewing. Each page is then available at an url such as http://www.example.com/pages.php?pid=123 Now, I want to redirect requests to http://www.example.com/pages.php?pid=123 to http://www.example.com/pages.php?pid=456.

I've already removed the pid=123 page from the db but because of the cms code the site still returns a 202 when some one tries to access the page. I thought I could use a 301 redirect in .htaccess to make the redirect work, i.e.:

redirect 301 pages.php?pid=123 http://www.example.com/pages.php?pid=456

but this doesn't work, Apache still return 202 when trying to fetch the pid=123 page. Also, I've tried using mod_rewrite, but it doesn't work:

RewriteRule ^pages.php?pid=123$ pages.php?pid=456 [R=301,L]

Any ideas what could be wrong and how I can fix the 301 redirect?

A: 

You can perform the redirect in PHP (which probably knows more about what to redirect where) using header().

Please note that ? is a special character used by regular expressions, so your regex matches pages.phppid=123 and pages.phppid=123.

Even then, I don't think the query string (including the ?pid=123 part) is used in the URL handled by RewriteRule, so you would need to use something like:

RewriteCond %{QUERY_STRING} ^pid=123$
RewriteRule ^pages.php$ pages.php?pid=456 [R=301,L]

This shouldn't work as is, but it should give you some ideas.

Victor Nicollet
Thanks for the feedback. I've already fixed the '?' part per Ivan Krechetov suggestion. The rewrite rule you suggest didn't unfortunatly work, still 202 and no redirect.
Evenz495
+1  A: 

Both the Redirect and RewriteRule directive work just on the URL path. In mod_alias (Redirect directive) you can not test the query and in mod_rewrite (RewriteRule directive) you need an additional RewriteCond directive:

RewriteCond %{QUERY_STRING} (^|&)pid=123(&|$)
RewriteRule ^pages\.php$ /pages.php?pid=456 [R=301,L]

But it would certainly be better if your CMS can handle such redirects since it’s your CMS that knows best what URLs are valid and what are not.

Gumbo
Thanks for the feedback. I've tried the rewrite above but it doesn't work. Still getting 202 and no redirect, only a page that loads the default php template.
Evenz495
@Evenz495: Do you use other rules that might get in conflict with this one?
Gumbo
This answer is golden. If you know that RewriteRule and Redirect don't work on query strings, everything suddenly falls into place and apache redirects are yet again easy. And one hour wrestling with RewriteRule trying to deal with query strings does not seem like much.
Paweł Gościcki