Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess 301 redirect issue with url variables

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.

like image 900
cardi777 Avatar asked Dec 21 '12 10:12

cardi777


People also ask

Does a 301 redirect change the URL?

A 301 signals a permanent redirect from one URL to another, meaning all users that request an old URL will be automatically sent to a new URL. A 301 redirect passes all ranking power from the old URL to the new URL, and is most commonly used when a page has been permanently moved or removed from a website.

How can I redirect and rewrite my URLs with an .htaccess file?

Use a 301 redirect . htaccess to point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "example.com" domain.

Should I enable 301 .htaccess redirect?

Because the WordPress 301 redirect is not always reliable, we recommend issuing the 301 redirect via your . htaccess file. Another benefit is that the . htaccess redirect is slightly faster than redirecting via PHP, because it is loaded even before the rest of the page.


1 Answers

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]
like image 105
Jon Lin Avatar answered Oct 05 '22 17:10

Jon Lin