Query string redirection with htaccess

こ雲淡風輕ζ 提交于 2019-12-30 10:30:13

问题


On a website I'm working on now I need to set up a redirection that takes a query string into consideration.

Example:

http://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!


回答1:


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:

  1. 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.

  2. 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.




回答2:


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


来源:https://stackoverflow.com/questions/7000110/query-string-redirection-with-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!