Home  >  Article  >  php教程  >  浅析Apache中RewriteCond规则参数的详细介绍

浅析Apache中RewriteCond规则参数的详细介绍

WBOY
WBOYOriginal
2016-06-13 11:43:351193browse

RewriteCond就像我们程序中的if语句一样,表示如果符合某个或某几个条件则执行RewriteCond下面紧邻的RewriteRule语句,这就是RewriteCond最原始、基础的功能,为了方便理解,下面来看看几个例子。

复制代码 代码如下:


RewriteEngine on
RewriteCond  %{HTTP_USER_AGENT}  ^Mozilla//5/.0.*
RewriteRule  index.php            index.m.php
RewriteCond  %{HTTP_USER_AGENT}  ^Lynx.*
RewriteRule  index.php            index.L.php
RewriteRule  index.php            index.b.php


上面语句的作用是当你是用FF浏览器访问index.php这个文件的时候,会自动让你访问到index.m.php这个文件,当你是用一些移动终端访问的 时候,会让你对index.php这个文件的访问实际访问的是index.L.php去,如果你是用其它的浏览器访问的时候,会让你跳到 index.b.php。在说形象一点,上面的语句就等同于程序里面的下面语句(依PHP语句为例):

复制代码 代码如下:


if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0')
{
//跳转到对index.m.php的访问
}
else if($_SERVER['HTTP_USER_AGENT'] == 'Lynx')
{
//跳转到对index.L.php的访问
}
else
//跳转到对index.b.php的访问


在看例2:
RewriteCond %{HTTP_REFERER} (www.test.cn)
RewriteRule (.*)$ test.php
上面语句的作用是如果你访问的上一个页面的主机地址是www.test.cn,则无论你当前访问的是哪个页面,都会跳转到对test.php的访问。
在看例三:

复制代码 代码如下:


RewriteCond %{REMOTE_HOST} ^host1.* [OR]
RewriteCond %{REMOTE_HOST} ^host2.* [OR]
RewriteCond %{REMOTE_HOST} ^host3.*
RewriteRule (.*)$ test.php


上面语句的作用是如果你的地址是host1或host2或host3的时候,则就跳到对test.php。从这里可以看出,RewriteCond语句之间默认的是AND,如果想要OR,则要明确的写出来。
下面是自己收藏的一些有用的重写规则:
RewriteCond %{REQUEST_FILENAME} !-f   //如果文件存在,就直接访问文件,不进行下面的RewriteRule.(不是文件或文件不存在就执行重写)
RewriteCond %{REQUEST_FILENAME} !-d   //#如果目录存在就直接访问目录不进行RewriteRule
RewriteCond %{REQUEST_URI} !^.*(/.css|/.js|/.gif|/.png|/.jpg|/.jpeg)$ //#如果是这些后缀的文件,就直接访问文件,不进行Rewrite
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn