如果页面是特定的,如何在.htaccess中执行If语句

时间:2017-11-22 00:59:43

标签: php apache .htaccess mod-rewrite

当我尝试使用if语句在页面具体时运行RewriteRule时,我得到this as response。我的apache服务器是2.4它也在我的屏幕截图中。我想在我的代码中做什么

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f


RewriteRule ^index$ ./index.php
RewriteRule ^zindex$ ./zindex.php
RewriteRule ^logout$ ./logout.php
RewriteRule ^login$ ./login.php
RewriteRule ^zlogin$ ./zlogin.php
RewriteRule ^404$ ./404.php





#write if statement to check pages that is being loaded else fire for new username

    <If "%{HTTP_HOST} == 'index.php' || %{HTTP_HOST} == 'ajaxsignlog.php' || %{HTTP_HOST} == 'ajaxsignlog1.php' || %{HTTP_HOST} == 'ajaxupload.php' || %{HTTP_HOST} == 'connect.php' || %{HTTP_HOST} == 'logout.php' || %{HTTP_HOST} == 'password.php' || %{HTTP_HOST} == 'top.php' || %{HTTP_HOST} == 'zindex.php' || %{HTTP_HOST} == 'ztop.php'">
                     // do not rewrite rule
    </If>
    <Else> //do some rewrite rules here
    RewriteRule ^ profile.php [NC,L]
    RewriteRule ^profile/([0-9a-zA-Z]+) profile.php?id=$1 [NC,L]

    RewriteRule ^ zprofile.php [NC,L]
    RewriteRule ^zprofile/([0-9a-zA-Z]+) zprofile.php?id=$1 [NC,L]
    </Else>

1 个答案:

答案 0 :(得分:1)

<块引用>
RewriteRule ^ profile.php [NC,L]
RewriteRule ^profile/([0-9a-zA-Z]+) profile.php?id=$1 [NC,L]

400 错误请求是由 <If>/<Else> 构造中的相对路径替换引起的。出于某种原因,在此上下文中重新添加的 directory-prefix 始终为 *If/(无论指令是在 <If><Else>块) - 在执行内部重写时可能会导致 400 Bad Request(如果执行外部重定向,则可能会导致 403 Forbidden)。

而且,在 <If>/<Else> 构造中,RewriteRule pattern 匹配绝对文件系统路径,而不是根相对 URL 路径。所以,上面的第二个指令永远不会匹配。

因此,如果这些限制/差异影响到您,请不要同时使用 mod_rewrite 和 Apache <If> 表达式。 <If> 表达式之外的指令如何受到影响还存在其他问题。 (就我个人而言,如果可能的话,我会避免将两者混用。)

另请参阅 my answer 以了解有关 ServerFault 的以下问题,其中更详细: https://serverfault.com/questions/1054363/bad-request-from-rewriterule-after-putting-if-directive

您不需要 <If>/<Else> 表达式来执行您想要的操作。 mod_rewrite 本身提供了执行此操作的机制,而无需其他工具。但是,具体如何实施取决于您要尝试做什么。

在问题中的示例中,如果请求与一系列 URL 中的一个匹配,您希望跳过一系列重写,那么您可以执行以下操作:

RewriteCond %{REQUEST_URI} =/index.php [OR]
RewriteCond %{REQUEST_URI} =/ajaxsignlog.php [OR]
RewriteCond %{REQUEST_URI} =/ajaxsignlog1.php [OR]
RewriteCond %{REQUEST_URI} =/ajaxupload.php [OR]
RewriteCond %{REQUEST_URI} =/connect.php [OR]
RewriteCond %{REQUEST_URI} =/logout.php [OR]
RewriteCond %{REQUEST_URI} =/password.php [OR]
RewriteCond %{REQUEST_URI} =/top.php [OR]
RewriteCond %{REQUEST_URI} =/zindex.php [OR]
RewriteCond %{REQUEST_URI} =/ztop.php
RewriteRule ^ - [S=10]

# 10 Rules follow that are skipped when any of the above URLs are requested
# :
# :

S=10 指令中的 RewriteRule 标志表示当任何前面的 URL 完全匹配时跳过的完整规则的数量。

另请参阅以下问题的 my answer,了解有关在 .htaccess 中实现条件分支的方法的更多想法: Grouping RewriteRule by RewriteCond with .htaccess