apache 使用RewriteCond获取2个以上的参数

fdx2calv  于 2022-11-16  发布在  Apache
关注(0)|答案(1)|浏览(138)

我有一个包含4个查询参数的URL:
https://address.com/bin/servlet?firstKey=firstValue&secondKey=secondValue&thirdKey=thirdValue
我会将此URLMap到路径变量:
https://address.com/content/firstValue/secondValue/thirdValue
这就是我要做的
RewriteCond %{QUERY_STRING} &?firstKey=([^&]+)&?secondKey=([^&]+) [NC]
然后重写规则:
RewriteRule ^/bin/servlet /content/%1/%2 [QSD,PT]
这是工作正常。

**但痛苦的是:**第三个参数,当我添加第三个关键像其他2个参数它不会工作。

RewriteCond %{QUERY_STRING} &?firstKey=([^&]+)&?secondKey=([^&]+)&?thirdKey=([^&]+) [NC]
RewriteRule ^/bin/servlet /content/%1/%2/%3 [QSD,PT]
ru9i0ody

ru9i0ody1#

您的实现存在许多问题,例如条件中“&”的使用。但通常,您可以使用所选策略检测和处理的参数数量没有限制。
我做了一些调整,这大概就是你要找的:

RewriteEngine on

RewriteCond %{QUERY_STRING} ^firstKey=([^&]+)&secondKey=([^&]+)&thirdKey=([^&]+)$
RewriteRule ^/?bin/servlet$ /content/%1/%2/%3 [R=301,QSD,L]

RewriteRule ^/?content/([^/]+)/([^/]+)/([^/]+)/?$ /bin/servlet?firstKey=$1&secondKey=$2&thirdKey=$3 [L,QSA]

很明显,这只处理使用 * 三个 * 参数的请求。可以将这种方法推广到能够处理动态数量的参数,但我建议不要这样做:通常情况下,最好是保持事情不那么复杂,所以如果需要的话,只需要为2个和4个参数添加相应的规则。2这样你就可以很容易地维护和扩展解决方案。
最新消息:
在下面的注解中,您询问是否可以捕获以任意顺序指定的参数值。当然,一切都是可能的,但事情会变得有点复杂。请看下面的示例:

RewriteEngine on

RewriteCond %{QUERY_STRING} (?:^|&)firstKey=([^&]+)(?:&|$)
RewriteRule ^/?bin/servlet$ - [E=FIRST_VAL:%1]
RewriteCond %{QUERY_STRING} (?:^|&)secondKey=([^&]+)(?:&|$)
RewriteRule ^/?bin/servlet$ - [E=SECOND_VAL:%1]
RewriteCond %{QUERY_STRING} (?:^|&)thirdKey=([^&]+)(?:&|$)
RewriteRule ^/?bin/servlet$ - [E=THIRD_VAL:%1]
RewriteRule ^/?bin/servlet$ /content/%{ENV:FIRST_VAL}/%{ENV:SECOND_VAL}/%{ENV:THIRD_VAL} [R=301,QSD,L]

RewriteRule ^/?content/([^/]+)/([^/]+)/([^/]+)/?$ /bin/servlet?firstKey=$1&secondKey=$2&thirdKey=$3 [L,QSA]

相关问题