Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite Query String

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.

like image 898
collimarco Avatar asked Dec 05 '25 17:12

collimarco


2 Answers

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]
like image 145
Vinko Vrsalovic Avatar answered Dec 08 '25 16:12

Vinko Vrsalovic


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]
like image 36
Gumbo Avatar answered Dec 08 '25 17:12

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!