RewriteCond 表示如果符合某个或某几个条件则执行RewriteCond下面紧邻的RewriteRule语句,几个例子。
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
上面语句的作用是当你是用firefox访问index.php这个文件的时候,会自动让你访问到index.m.php这个文件,当你是用一些移动终端访问的 时候,会让你对index.php这个文件的访问实际访问的是index.L.php去,如果你是用其它的浏览器访问的时候,会让你跳到 index.b.php。在说形象一点,上面的语句就等同于程序里面的下面语句(依PHP语句为例):
再看例2:
RewriteCond %{HTTP_REFERER} (www.test.cn)
RewriteRule (.*)$ test.php
上面语句的作用是如果你访问的上一个页面的主机地址是www.test.cn,则无论你当前访问的是哪个页面,都会跳转到对test.php的访问。 再看例3:
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
Apache mod_rewrite模块处理query strings 时会有些让人困惑. 以下是RewriteRule的官方文档说明:
qsappend|QSA’ (query string append)
This flag forces the rewrite engine to append a query string part of the substitution string to the existing string, instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.
让我们尝试通过query string来跳转页面. 我们的重写规则如下:
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^page\.php$ http://mydomain.site/page/%1.php [R=302,L]
根据官方文档, 输出似乎应该是这样的:
/page.php?id=37 -TO- http://mydomain.site/page/37.php
/page.php?id=40 -TO- http://mydomain.site/page/40.php
# and so on
/page.php?id=37 -TO- http://mydomain.site/page/37.php?id=37
/page.php?id=40 -TO- http://mydomain.site/page/40.php?id=40
# and so on
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^page\.php$ http://mydomain.site/page/%1.php? [R=302,L]
Keep original query (default behavior)
RewriteRule ^page\.php$ /target.php [L]
# from http://example.com/page.php?foo=bar
# to http://example.com/target.php?foo=bar
Discard original query
RewriteRule ^page\.php$ /target.php? [L]
# from http://example.com/page.php?foo=bar
# to http://example.com/target.php
Replace original query
RewriteRule ^page\.php$ /target.php?bar=baz [L]
# from http://example.com/page.php?foo=bar
# to http://example.com/target.php?bar=baz
Append new query to original query
RewriteRule ^page\.php$ /target.php?bar=baz [QSA,L]
# from http://example.com/page.php?foo=bar
# to http://example.com/target.php?foo=bar&bar=baz