.htaccess规则在重定向中跳过子文件夹

时间:2014-06-29 03:54:49

标签: regex .htaccess

这是我的重写规则:

RewriteEngine on
RewriteRule ^dev/([^/]+)/ dev/index.php?test=$1 [NC]

但是,不是将网址从www.test.com/dev/asdf更改为www.test.com/dev/index.php?test=asdf,而是我们获得www.test.com/index.php?test=asdf。所以基本上只重写了重写规则中的dev/部分。

预期的效果是将dev/variable/解析为get变量,因此它会更改为dev/index.php?test=variable

2 个答案:

答案 0 :(得分:1)

可能有以下几种情况:.htaccess位于错误的文件夹中,错误的RewriteBase位于其他地方,或者网址被其他规则重写。

请务必将.htaccess放入DOCUMENT_ROOT文件夹(dev上方的文件夹)。

然后试试这个:

RewriteEngine on
RewriteBase /
RewriteRule ^dev/([^/]+)/ dev/index.php?test=$1 [NC,L]

答案 1 :(得分:0)

请尝试使用此mod_rewrite规则集:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(dev/index.php)$ [NC]
RewriteRule ^dev/?([^/]*)$ /dev/index.php?test=$1 [R,L,NC]

具有RewriteCond的第二行是为了确保您没有dev/[something]dev/index.php的无限循环,这将导致内部服务器错误。 R标志将实际重定向设置为/dev/index.php?test=,而不是仅仅在后台传递参数。

R标志的一个好处是,您可以使用命令行中的curl -I来调试此内容,以显示返回的实际标头。我在我当地的MAMP使用localhost:8888,FWIW:

curl -I localhost:8888/dev/asdf

现在生成的标题如下:

HTTP/1.1 302 Found
Date: Sun, 29 Jun 2014 04:15:31 GMT
Server: Apache/2.2.23 (Unix) mod_ssl/2.2.23 OpenSSL/0.9.8y DAV/2 PHP/5.4.10
Location: http://localhost:8888/dev/index.php?test=asdf
Content-Type: text/html; charset=iso-8859-1

HTTP/1.1 302 Found表示将发生302临时重定向。 Location标题显示http://localhost:8888/dev/index.php?test=asdf的正确最终目的地。

然后在我的测试设置中,我放置了一个包含这个简单PHP代码的dev/index.php文件:

<?php

echo '<pre>';
print_r($_GET);
echo '</pre>';

?>

因此,对localhost:8888/dev/asdf的调用会创建http://localhost:8888/dev/index.php?test=asdf的最终网址,并且该PHP脚本的输出显示asdf已正确传递:

Array
(
    [test] => asdf
)