RewriteCond 内的 %N 反向引用 [英] %N backreference inside RewriteCond
问题描述
我正在研究一个虚拟域系统.我有一个通配符 DNS 设置为 *.loc
,我正在尝试处理我的 .htaccess
文件.以下代码有效:
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}
.我尝试使用此代码:
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/
导致我的代码抛出内部服务器错误.我知道这是因为我的代码中的 %N 但有没有办法使用它?我需要这一行,否则我的代码会因内部重定向而失败.
But the line RewriteCond %{REQUEST_URI} !^/%3/
causes my code to throw 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 = r
).
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/?
.这个正则表达式本质上是说:在 :: 之前匹配和分组第一个文本块,然后确保 :: 之后的文本块> 以 /(first block)
" 开头.
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]
这篇关于RewriteCond 内的 %N 反向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!