301 Redirect (.htaccess)

tomaszjot

Membership Suspended
Dec 22, 2009
1,938
77
0
Albany Plantation
I have an old website with non-firendly URL structure. It gets some traffic so I would like to redirect it to new domain.

Now, what I want to achieve is to redirect pages on old domain to the pages on new domain, something like this:

http://olddomain/product.php?id=some-product

to

http://newdomain.com/old-products/some-product

I know how to change this on the same domain but how to redirect it to pages on new domain?

Any help appreciated. Thanks.
 


More difficult than it seems at first, as RewriteRule doesn't see url query parameters.

So, the "obvious solution", below, doesn't work.

Code:
# this is wrong, and won't work, RewriteRule doesn't see url parameters
RewriteEngine on
RewriteRule ^product.php?id=(.*)$ http://newdomain.com/old-products/$1 [R=301,L]
# above is wrong...don't use

There's a workaround though, with RewriteCond matching, and then a %n type backreference. The question mark at the end of the new url forces it to drop the query params, which it will otherwise tack on if you omit it.

Code:
RewriteCond %{QUERY_STRING} id=(.+)
RewriteRule ^product.php$ http://newdomain.com/old-products/%1? [R=301,L]

You may need a fancier regex to match the id param if there are other params in the query. If that's the only one, this should work fine.
 
  • Like
Reactions: tomaszjot
More difficult than it seems at first, as RewriteRule doesn't see url query parameters.

So, the "obvious solution", below, doesn't work.

Code:
# this is wrong, and won't work, RewriteRule doesn't see url parameters
RewriteEngine on
RewriteRule ^product.php?id=(.*)$ http://newdomain.com/old-products/$1 [R=301,L]
# above is wrong...don't use
There's a workaround though, with RewriteCond matching, and then a %n type backreference. The question mark at the end of the new url forces it to drop the query params, which it will otherwise tack on if you omit it.

Code:
RewriteCond %{QUERY_STRING} id=(.+)
RewriteRule ^product.php$ http://newdomain.com/old-products/%1? [R=301,L]
You may need a fancier regex to match the id param if there are other params in the query. If that's the only one, this should work fine.

Thanx!