htaccess 301 redirect issue with url variables

cardi777 picture cardi777 · Dec 21, 2012 · Viewed 27.2k times · Source

If I use this code, it's successful:

Redirect 301 /products.php http://website.com.au/product_123.php

But if I do this, it isn't:

Redirect 301 /products.php?id=123 http://website.com.au/product_123.php

Note the variable in the url is what's causing it to fail.

What am I doing wrong? Is there another way to do this? I really need the urls variables.

Answer

Jon Lin picture Jon Lin · Dec 21, 2012

You can't put query string parameters in the source URI path of the Redirect directive. You'll have to use mod_rewrite's %{QUERY_STRING} variable for that:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=123$
RewriteRule ^/?product\.php$ http://website.com.au/product_123.php? [L,R=301]

Or to make it more general:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=([^&]+)
RewriteRule ^/?product\.php$ http://website.com.au/product_%1.php? [L,R=301]