2

I have this URL:

oldsite.example/profile.php?uid=10

I would like to rewrite it to:

newsite.example/utenti/10

How can I do that?

I wrote this:

RewriteCond %{QUERY_STRING} ^uid=([0-9]+)$
RewriteRule ^profile\.php$ http://www.newsite.example/utenti/$1 [R=301,L]

But $1 matches the full query string and not just the user id.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
collimarco
  • 34,231
  • 36
  • 108
  • 142

2 Answers2

9

To use matches in the rewrite conditions, you have to use %1 instead of $1. Also, if you wish to remove the rest of the query string you have to append a ?

RewriteCond %{QUERY_STRING} ^uid=([0-9]+)$
RewriteRule ^profile\.php$ http://www.newsite.example/utenti/%1? [R=301,L]
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
4

The $n only refer to the matches of the RewriteRule directive. Use %n to reference the matches of the corresponding RewriteCond directive.

Additionally you need to specify an empty query for the substitution. Otherwise the original query will be used.

And if you want to have the rest of the query to stay intact, use this rule:

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)uid=([0-9]+)(.*)
RewriteRule ^profile\.php$ http://newsite.example/utenti/%3?%1%4 [R=301,L]
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Gumbo
  • 643,351
  • 109
  • 780
  • 844