Query string redirection with htaccess
On a website I'm working on now I need to set up a redirection that takes a query string into consideration.
Example:
http:开发者_StackOverflow社区//www.domain.com/?id=86&name=John&ref=12d34 -> http://www.domain.com/?ref=12d34
http://www.domain.com/?ref=593x56&id=935 -> http://www.domain.com/?ref=593x56
http://www.domain.com/?ref=3v77l32 -> http://www.domain.com/?ref=3v77l32
So basically I need to find the ref parameter and it's value (whatever it's length) and append only that part to the new URL. The issue is the the ref parameter can appear anywhere within the URL.
Any help or guidance would be very much appreciated!
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=yesto the same URL but withrefparameter only:http://www.example.com/hello.php?ref=12d34888.It will do nothing if only
refparameter is present or no parameter at all, e.g.http://www.example.com/hello.php?ref=12d34888orhttp://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.
RewriteEngine On
RewriteRule ref=(.*?) /?ref=$1 [L]
is about as simple as it guess, but this will screw up if the ref query var isn't the last thing in the line - it'll slurp up everything after ref= and redirect that to, so
/blah&ref=abc&blahblahblah
would turn into
/ref=abc&blahblahblah
加载中,请稍侯......
精彩评论