根据路径和查询字符串使用mod_rewrite比较并重写URL [英] Compare and rewrite URL with mod_rewrite based on path and query string

查看:76
本文介绍了根据路径和查询字符串使用mod_rewrite比较并重写URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方案中的URL

I have URLs in a scheme

/([0-9]*)/some/path/script.jsf?someId=([0-9]*)

,如果$ 1与$ 2不匹配,我想将用户重定向到$ 2.例如,如果用户请求

and I'd like to redirect to $2 the user if $1 doesn't match $2. So for example if the user requests

/1/some/path/script.jsf?someId=1

一切都很好,不应重定向用户,但如果用户请求

everthing is fine and the user shouldn't be redirected but if the user requests

/1/some/path/script.jsf?someId=2

应该将用户重定向到

/2/some/path/script.jsf?someId=2

我尝试过以下规则:

RewriteCond %{REQUEST_URI} ^/([0-9]*)/
RewriteCond %{QUERY_STRING} someId=([0-9]*)
RewriteCond %1 !%2
RewriteRule (.*) /%2/some/path/script.jsf?someId=%2 [R]

但是%2似乎总是空的.因此,我尝试了以下规则:

but %2 seems always empty. So I've tried this rule:

RewriteCond %{REQUEST_URI} ^/([0-9]*)/some/path/script.jsf?someId=([0-9]*)
RewriteCond %1 !%2
RewriteRule (.*) /%2/)/some/path/script.jsf?someId=%2 [R]

推荐答案

%n仅访问来自

当前条件集中最后匹配的RewriteCond.

这就是为什么您的%2在第一组规则中总是显得空白的原因.

That's why your %2 always seems empty in your first set of rules.

您的第二次尝试解决了RewriteCond %1 !%2的问题,但是您不能在RewriteRule中引用%2,因为它再次引用了最后匹配的RewriteCond .

Your second attempt gets around this problem for the RewriteCond %1 !%2, but you can't refer to %2 in your RewriteRule, as it refers to, again, the last matched RewriteCond.

如果您正在运行Apache 2,则有一个非常简单的方法来使用否定的超前断言:

If you're running Apache 2, there's a very simple way to do this using a negative lookahead assertion:

RewriteRule ^/([0-9]*)/some/path/script.jsf?someId=(?!$1(?:$|[^0-9]))([0-9]*) /$2/some/path/script.jsf?someId=$2 [R]

重要的是

(?!$1(?:$|[^0-9]))

断言下一个字符序列不能完全是$1中的数字. ($|[^0-9]位确保考虑到尾随数字.)

which asserts that the next sequence of characters cannot be exactly the number in $1. (The $|[^0-9] bit assures that trailing numbers are considered.)

这篇关于根据路径和查询字符串使用mod_rewrite比较并重写URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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