%N反向引用里面的RewriteCond

%N反向引用里面的RewriteCond

本文介绍了%N反向引用里面的RewriteCond的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个虚拟域的系统。我有一个通配符DNS设置为 *。LOC ,和我想在我的的.htaccess 文件。下面code工作:

I'm working on a virtual domain system. I have a wildcard DNS set up as *.loc, and I'm trying to work on my .htaccess file. The following code works:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?example\.loc$ [NC]
RewriteCond %{REQUEST_URI} !^/example/
RewriteRule (.*) /example/$1 [L,QSA]

不过,我想这对任何事情我把工作。但是,我需要的%{REQUEST_URI} 核对发现作为域的文本。我试图用这个code:

But, I want this to work with anything I put in. However, I need the %{REQUEST_URI} checked against the text found as the domain. I tried using this code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?([a-zA-Z0-9-]*.)?([a-zA-Z0-9-]+)\.loc$ [NC]
RewriteCond %{REQUEST_URI} !^/%3/
RewriteRule (.*) /%3/$1 [L,QSA]

不过,该行的RewriteCond%{REQUEST_URI}!^ / 3%/ 使我的code,以通过内部服务器错误。我明白这是我的code中的%N,因为,但有什么办法,我可以使用它?我需要这一行,否则我的code从内部重定向失败。

But the line RewriteCond %{REQUEST_URI} !^/%3/ causes my code to through an Internal Server Error. I understand this is because of the %N in my code, but is there a way I can work with it? I need this line, otherwise my code fails from internal redirects.

我希望这是有道理的人。所有我需要的是能够反向引用一个的RewriteCond在接下来的RewriteCond。

I hope this makes sense to someone. All I need is to be able to backreference a RewriteCond in a following RewriteCond.

推荐答案

有2件事情,你在做什么错在这里。

There's 2 things that you are doing wrong here.

首先,你的%{HTTP_HOST} 正则表达式是没有好处的。你需要躲避点,否则他们将被视为任何字符,这不是一个新行。这实际上使得%3 反向引用的主机名的TLD前的最后一个字符(如的http://blah.bar.loc %3 = 研究)。

First, your %{HTTP_HOST} regex is no good. You need to escape the . dots otherwise they'll be treated as "any character that's not a newline". This essentially makes the %3 backreference the last character of the hostname before the TLD (e.g. http://blah.bar.loc, %3 = r).

二,你不能在的RewriteCond ,只有左侧的字符串的正则表达式使用反向引用,这有点怪异的限制。但是,您可以使用 \ 1 引用的正则表达式,这样就可以构造一个聪明的左侧字符串匹配。像 3%::%{REQUEST_URI} ,然后你可以匹配这样的:(。*?) ^ :: / \ 1 / ?。这正则表达式基本上说:文字的比赛和小组的第一个块的的在 :: ,然后使文本的确认块以下的 :: 开头 /(第一块)

Second, you can't use backreferences in the regex of a RewriteCond, only the left side string, it's sort of a weird limitation. However, you can use the \1 references, in the regex so that you can construct a clever left side string to match against. Something like %3::%{REQUEST_URI} and then you can match like this: !^(.*?)::/\1/?. This regex essentially says: "match and group the first block of text before the ::, then make sure the block of text following the :: starts with /(first block)".

所以,你的规则应该是这样的:

So your rules should look like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?([a-zA-Z0-9-]*\.)?([a-zA-Z0-9-]+)\.loc$ [NC]
RewriteCond %3::%{REQUEST_URI} !^(.*?)::/\1/?
RewriteRule (.*) /%3/$1 [L,QSA]

这篇关于%N反向引用里面的RewriteCond的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:06