Apache 的 RewriteRule 的 $1 替换不是 return 第一个匹配的表达式
$1 substitution for Apache's RewriteRule doesn't return the first matched expression
我到处都读到 Apache 的重写引擎中的模式替换对正则表达式如预期的那样工作,所以我尝试了:
.htaccess:
RewriteRule (.*) index.php?route=
但是对于在 get var route 中对 domain.com/some/url
的请求,我得到 index.php
而不是 some/url
在 http var REDIRECT_QUERY_STRING
我得到 route=some/url
但是在 QUERY_STRING
我得到 route=index.php
这里可能出了什么问题?
PS: [=19=]
也 returns index.php
如果我使用 RewriteRule . index.php?route=
,我得到 route=i
,无论请求如何 URL.
</code> 正在按预期工作,但问题是您对这种模式的使用:</p>
<pre><code>(.*)
匹配任何内容。您的重写规则 实际上循环并运行两次 因为您没有任何 RewriteCond
来预循环。
- 首先它为 URI=
some/url
运行并且 URI 变为 index.php
而 </code> 变为 <code>some/url
- 第二次为 URI=
index.php
运行并且 </code> 变为 <code>index.php
您可以使用此规则来修复此行为:
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) index.php?route= [L,QSA]
或者,如果您想将现有文件和目录重写为 index.php
,则使用:
RewriteRule ^((?!index\.php$).*)$ index.php?route= [L,QSA,NC]
这会将除 index.php
之外的所有内容重写为 index.php
。
我到处都读到 Apache 的重写引擎中的模式替换对正则表达式如预期的那样工作,所以我尝试了:
.htaccess:
RewriteRule (.*) index.php?route=
但是对于在 get var route 中对 domain.com/some/url
的请求,我得到 index.php
而不是 some/url
在 http var REDIRECT_QUERY_STRING
我得到 route=some/url
但是在 QUERY_STRING
我得到 route=index.php
这里可能出了什么问题?
PS: [=19=]
也 returns index.php
如果我使用 RewriteRule . index.php?route=
,我得到 route=i
,无论请求如何 URL.
</code> 正在按预期工作,但问题是您对这种模式的使用:</p>
<pre><code>(.*)
匹配任何内容。您的重写规则 实际上循环并运行两次 因为您没有任何 RewriteCond
来预循环。
- 首先它为 URI=
some/url
运行并且 URI 变为index.php
而</code> 变为 <code>some/url
- 第二次为 URI=
index.php
运行并且</code> 变为 <code>index.php
您可以使用此规则来修复此行为:
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) index.php?route= [L,QSA]
或者,如果您想将现有文件和目录重写为 index.php
,则使用:
RewriteRule ^((?!index\.php$).*)$ index.php?route= [L,QSA,NC]
这会将除 index.php
之外的所有内容重写为 index.php
。