开发者

.htaccess 301 redirect not working

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开发者_StackOverflow社区 the 301 redirect?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜