Many posters have problems debugging their RewriteRule and RewriteCond statements within their .htaccess files. Most of these are using a shared hosting service and therefore don't have access to the root server configuration. They cannot avoid using .htaccess files for rewriting and cannot enable a RewriteLogLevel" as many respondents suggest. Also there are many .htaccess-specific pitfalls and constraints are aren't covered well. Setting up a local test LAMP stack involves too much of a learning curve for most.

所以我的问题是我们建议他们如何自己调试他们的规则。以下是我的一些建议。其他建议将不胜感激。

Understand that the mod_rewrite engine cycles through .htaccess files. The engine runs this loop: do execute server and vhost rewrites (in the Apache Virtual Host Config) find the lowest "Per Dir" .htaccess file on the file path with rewrites enabled if found(.htaccess) execute .htaccess rewrites (in the user's directory) while rewrite occurred So your rules will get executed repeatedly and if you change the URI path then it may end up executing other .htaccessfiles if they exist. So make sure that you terminate this loop, if necessary by adding extra RewriteCond to stop rules firing. Also delete any lower level .htaccess rewrite rulesets unless explicitly intent to use multi-level rulesets. Make sure that the syntax of each Regexp is correct by testing against a set of test patterns to make sure that is a valid syntax and does what you intend with a fully range of test URIs. See answer below for more details. Build up your rules incrementally in a test directory. You can make use of the "execute the deepest .htaccess file on the path feature" to set up a separate test directory (tree) and debug rulesets here without screwing up your main rules and stopping your site working. You have to add them one at a time because this is the only way to localise failures to individual rules. Use a dummy script stub to dump out server and environment variables. (See Listing 2)If your app uses, say, blog/index.php then you can copy this into test/blog/index.php and use it to test out your blog rules in the test subdirectory. You can also use environment variables to make sure that the rewrite engine in interpreting substitution strings correctly, e.g. RewriteRule ^(.*) - [E=TEST0:%{DOCUMENT_ROOT}/blog/html_cache/$1.html] and look for these REDIRECT_* variables in the phpinfo dump. BTW, I used this one and discovered on my site that I had to use %{ENV:DOCUMENT_ROOT_REAL} instead. In the case of redirector looping REDIRECT_REDIRECT_* variables list the previous pass. Etc.. Make sure that you don't get bitten by your browser caching incorrect 301 redirects. See answer below. My thanks to Ulrich Palha for this. The rewrite engine seems sensitive to cascaded rules within an .htaccess context, (that is where a RewriteRule results in a substitution and this falls though to further rules), as I found bugs with internal sub-requests (1), and incorrect PATH_INFO processing which can often be prevents by use of the [NS], [L] and [PT] flags.

还有什么评论或建议吗?

清单1——phpinfo

<?php phpinfo(INFO_ENVIRONMENT|INFO_VARIABLES);

当前回答

确保每个Regexp的语法是正确的

通过对一组测试模式进行测试,以确保语法有效,并对所有测试uri执行您想要的操作。

See regexpCheck.php below for a simple script that you can add to a private/test directory in your site to help you do this. I've kept this brief rather than pretty. Just past this into a file regexpCheck.php in a test directory to use it on your website. This will help you build up any regexp and test it against a list of test cases as you do so. I am using the PHP PCRE engine here, but having had a look at the Apache source, this is basically identical to the one used in Apache. There are many HowTos and tutorials which provide templates and can help you build your regexp skills.

清单1——regexpCheck.php

<html><head><title>Regexp checker</title></head><body>
<?php 
    $a_pattern= isset($_POST['pattern']) ? $_POST['pattern'] : "";
    $a_ntests = isset($_POST['ntests']) ? $_POST['ntests'] : 1;
    $a_test   = isset($_POST['test']) ? $_POST['test'] : array();
    
    $res = array(); $maxM=-1; 
    foreach($a_test as $t ){
        $rtn = @preg_match('#'.$a_pattern.'#',$t,$m);
        if($rtn == 1){
            $maxM=max($maxM,count($m));
            $res[]=array_merge( array('matched'),  $m );
        } else {
            $res[]=array(($rtn === FALSE ? 'invalid' : 'non-matched'));
        }
    } 
?> <p>&nbsp; </p>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>">
    <label for="pl">Regexp Pattern: </label>
    <input id="p" name="pattern" size="50" value="<?php echo htmlentities($a_pattern,ENT_QUOTES,"UTF-8");;?>" />
    <label for="n">&nbsp; &nbsp; Number of test vectors: </label>
    <input id="n" name="ntests"  size="3" value="<?php echo $a_ntests;?>"/>
    <input type="submit" name="go" value="OK"/><hr/><p>&nbsp;</p>
    <table><thead><tr><td><b>Test Vector</b></td><td>&nbsp; &nbsp; <b>Result</b></td>
<?php 
    for ( $i=0; $i<$maxM; $i++ ) echo "<td>&nbsp; &nbsp; <b>\$$i</b></td>";
    echo "</tr><tbody>\n";
    for( $i=0; $i<$a_ntests; $i++ ){
        echo '<tr><td>&nbsp;<input name="test[]" value="', 
            htmlentities($a_test[$i], ENT_QUOTES,"UTF-8"),'" /></td>';
        foreach ($res[$i] as $v) { echo '<td>&nbsp; &nbsp; ',htmlentities($v, ENT_QUOTES,"UTF-8"),'&nbsp; &nbsp; </td>';}
        echo "</tr>\n";
    }
?> </table></form></body></html>

其他回答

下面是一些关于测试规则的额外技巧,可以简化共享主机上用户的调试

1. 使用伪用户代理

在测试一个新规则时,添加一个条件,以只使用一个伪用户代理执行它,您将在请求中使用这个假用户代理。这样就不会影响到你网站上的其他人。

e.g

#protect with a fake user agent
RewriteCond %{HTTP_USER_AGENT}  ^my-fake-user-agent$
#Here is the actual rule I am testing
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC] 
RewriteRule ^ http://www.domain.com%{REQUEST_URI} [L,R=302] 

如果您正在使用Firefox,您可以使用用户代理切换器来创建假用户代理字符串并进行测试。

2. 在测试完成之前不要使用301

我见过很多帖子,人们仍然在测试他们的规则,他们使用的是301。不喜欢。

如果你没有在你的网站上使用建议1,那么不仅是你,而且当时访问你网站的任何人都将受到301的影响。

请记住,它们是永久的,并被浏览器积极缓存。 在确定之前,先用302,然后再换成301。

3.请记住,301缓存在您的浏览器中

如果您的规则不起作用,并且看起来对您来说是正确的,并且您没有使用建议1和2,那么在清除浏览器缓存后或在私人浏览时重新测试。

4. 使用HTTP捕获工具

使用Fiddler之类的HTTP捕获工具来查看浏览器和服务器之间的实际HTTP流量。

虽然其他人可能会说您的网站看起来不正确,但您可以看到并报告所有的图像、css和js都返回404错误,从而迅速缩小问题范围。

虽然其他人会报告说你从URL A开始,结束于URL C,你将能够看到他们从URL A开始,被302重定向到URL B和301重定向到URL C。即使URL C是最终目标,你也会知道这对SEO是不利的,需要修复。

您将能够看到在服务器端设置的缓存头,重放请求,修改请求头以测试....


也许调试重写规则的最好方法是根本不使用重写规则,而是将URL处理从htaccess文件推迟到PHP文件(让我们称之为router.php)。然后,您可以使用PHP进行任何您喜欢的操作,并使用适当的错误检测和常规的调试方法。这甚至运行得更快,因为您不必使用重写模块。

对于文件系统中没有的URL,要立即将控制权从.htaccess转移到router.php,只需在.htaccess中放入以下一行:

FallbackResource router.php

是的,真的很简单。是的,它确实有效。试一试。

注意:你可能需要在你的。htaccess文件中使用一个ErrorDocument指令来在HTTP状态404时显式地将某些url的控制权传递给你的router.php文件,特别是如果你继承了处理状态404的父htaccess文件。这样一来,将控制权传递到路由器文件总共需要两行。

在线。htaccess重写测试

我在谷歌上找到了这个RegEx的帮助,它为我节省了很多时间,每次我做一个小的修改都要上传新的。htaccess文件。

来自网站:

htaccess测试仪 要测试你的htaccess重写规则,只需填写你应用规则的url,把你的htaccess的内容放在更大的输入区域,然后按“现在检查”按钮。

如果你打算在. htaccess中编写多行规则, 甚至不要考虑尝试那些热修复方法来调试它。

我浪费了几天时间设置多条规则,没有日志的反馈,最终只能放弃。 我在我的PC上安装了Apache,将整个站点复制到它的硬盘上,并使用日志快速整理了整个规则集。 然后我回顾了我的旧规则,这些规则一直在起作用。我发现他们并没有真正按照要求去做。定时炸弹,地址稍有不同。

重写规则中有很多陷阱,这根本不是一个直接的逻辑问题。 你可以在十分钟内启动并运行Apache,它是10MB,良好的许可证,*NIX/WIN/MAC就绪,甚至不需要安装。 此外,检查服务器的标题行,如果Apache是旧的,请从存档中获取相同版本的Apache。我的OP仍然在2.0;很多东西是不支持的。

确保每个Regexp的语法是正确的

通过对一组测试模式进行测试,以确保语法有效,并对所有测试uri执行您想要的操作。

See regexpCheck.php below for a simple script that you can add to a private/test directory in your site to help you do this. I've kept this brief rather than pretty. Just past this into a file regexpCheck.php in a test directory to use it on your website. This will help you build up any regexp and test it against a list of test cases as you do so. I am using the PHP PCRE engine here, but having had a look at the Apache source, this is basically identical to the one used in Apache. There are many HowTos and tutorials which provide templates and can help you build your regexp skills.

清单1——regexpCheck.php

<html><head><title>Regexp checker</title></head><body>
<?php 
    $a_pattern= isset($_POST['pattern']) ? $_POST['pattern'] : "";
    $a_ntests = isset($_POST['ntests']) ? $_POST['ntests'] : 1;
    $a_test   = isset($_POST['test']) ? $_POST['test'] : array();
    
    $res = array(); $maxM=-1; 
    foreach($a_test as $t ){
        $rtn = @preg_match('#'.$a_pattern.'#',$t,$m);
        if($rtn == 1){
            $maxM=max($maxM,count($m));
            $res[]=array_merge( array('matched'),  $m );
        } else {
            $res[]=array(($rtn === FALSE ? 'invalid' : 'non-matched'));
        }
    } 
?> <p>&nbsp; </p>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>">
    <label for="pl">Regexp Pattern: </label>
    <input id="p" name="pattern" size="50" value="<?php echo htmlentities($a_pattern,ENT_QUOTES,"UTF-8");;?>" />
    <label for="n">&nbsp; &nbsp; Number of test vectors: </label>
    <input id="n" name="ntests"  size="3" value="<?php echo $a_ntests;?>"/>
    <input type="submit" name="go" value="OK"/><hr/><p>&nbsp;</p>
    <table><thead><tr><td><b>Test Vector</b></td><td>&nbsp; &nbsp; <b>Result</b></td>
<?php 
    for ( $i=0; $i<$maxM; $i++ ) echo "<td>&nbsp; &nbsp; <b>\$$i</b></td>";
    echo "</tr><tbody>\n";
    for( $i=0; $i<$a_ntests; $i++ ){
        echo '<tr><td>&nbsp;<input name="test[]" value="', 
            htmlentities($a_test[$i], ENT_QUOTES,"UTF-8"),'" /></td>';
        foreach ($res[$i] as $v) { echo '<td>&nbsp; &nbsp; ',htmlentities($v, ENT_QUOTES,"UTF-8"),'&nbsp; &nbsp; </td>';}
        echo "</tr>\n";
    }
?> </table></form></body></html>