在 RewriteRule 中引用多个 RewriteCond 的捕获组 [英] Reference capture groups of multiple RewriteCond in RewriteRule

查看:37
本文介绍了在 RewriteRule 中引用多个 RewriteCond 的捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有多个 RewriteCond 链接在一起时,只有最后一个 RewriteCond 的捕获组可以被 %0-%9 引用.

When I have multiple RewriteCond chained together, only the capture groups of the last RewriteCond can be referenced with %0-%9.

在下面的问题中,url的查询字符串中的参数可以是任意顺序.要将它们解析为花哨的 url,我需要分别匹配查询字符串中的每个参数:

In the following problem the parameters in the query string of the url can be in any order. To parse them into a fancy url I would need to match each parameter in the query string individually:

RewriteCond %{QUERY_STRING} param1=([^&]+)
RewriteCond %{QUERY_STRING} param2=([^&]+)
RewriteCond %{QUERY_STRING} param3=([^&]+)
RewriteRule ^foo$ bar/%1/%2/%3/ [R]

就像我指出的那样......这行不通.为了解决这个问题,我可以在下一个 RewriteCond 中引用前一个 RewriteCond 的捕获组,并将每个参数传播"到实际的 RewriteRule:

Like I pointed out... this doesn't work. To fix this, I could reference the capture group of the previous RewriteCond in the next RewriteCond and 'propagate' each parameter to the actual RewriteRule:

RewriteCond %{QUERY_STRING} param1=([^&]+)
RewriteCond %1&%{QUERY_STRING} ^([^&]*)&.*param2=([^&]+)
RewriteCond %1&%2&%{QUERY_STRING} ^([^&]*)&([^&]*)&.*param3=([^&]+)
RewriteRule ^foo$ bar/%1/%2/%3/ [R]

这应该可行,但是对于每个附加参数,它都会变得更加混乱.另一种解决方案可能是解析一个参数并在每个参数之后重定向客户端(导致冗长的重定向链,我想避免这种情况).

This should work, but for each additional parameter it get's messier. An other solution could possibly be parsing one parameter and redirecting the client after each parameter (resulting in a lengthy chain of redirects, which I would like to avoid).

是否有一种更简洁的方法来访问 RewriteRule 中所有 RewriteCond 的捕获组(例如,是否可以命名它们或将它们分配给一个变量,以便我可以在其他地方引用它们?)

Is there an cleaner way of accessing the capture groups of all RewriteCond's in the RewriteRule (e.g. is it possible to name them or assign them to a variable so I can reference them somewhere else?)

推荐答案

您可以尝试在重写条件中构建目标 URL:

You could try constructing the target URL inside the rewrite conditions:

RewriteCond ##%{QUERY_STRING}      (.*)##(|.*&)param1=([^&]+)
RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param2=([^&]+)
RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param3=([^&]+)
RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param4=([^&]+)
RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param5=([^&]+)
RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param6=([^&]+)

RewriteRule ^foo$ /bar%1/%3? [L,R]

当我尝试请求时:

/foo?param1=a&param2=b&param6=3&param3=4&param5=5&param4=6

我被重定向到:

/bar/a/b/4/6/5/3

添加任何额外的必需查询字符串参数不会让它看起来比现在更混乱.

Adding any additional required query string parameters won't make it look any more messy than it already is.

这篇关于在 RewriteRule 中引用多个 RewriteCond 的捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆