RewriteRule
does not work with query string directly -- you have to use RewriteCond
for that.
Here is the rule -- it will redirect (301 Permanent Redirect) ANY URL that has more than 1 parameter in query string and 1 of them is ref
RewriteEngine On
RewriteCond %{QUERY_STRING} (^|&)ref=([^&]*)(&|$)
RewriteCond %{QUERY_STRING} !^ref=([^&]*)$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}?ref=%2 [R=301,L]
For example:
It will redirect http://www.example.com/hello.php?id=86&name=John&ref=12d34888&me=yes
to the same URL but with ref
parameter only: http://www.example.com/hello.php?ref=12d34888
.
It will do nothing if only ref
parameter is present or no parameter at all, e.g. http://www.example.com/hello.php?ref=12d34888
or http://www.example.com/hello.php
.
If such redirect should only work for website root hits, then change the RewriteRule
line to this:
RewriteRule ^$ http://%{HTTP_HOST}/?ref=%2 [R=301,L]
(this is if placed in .htaccess file in website root folder -- if placed in server config / virtual host context the rule needs to be slightly tweaked).
http://www.example.com/?id=86&name=John&ref=12d34888&me=yes
-> http://www.example.com/?ref=12d34888
If it has to be redirected to another domain, then replace %{HTTP_HOST}
by domain specific name, e.g:
RewriteRule ^$ http://www.exampe.com/?ref=%2 [R=301,L]
It all has been tested before posting.