做网站开发这么长时间,对于Apache 的 Rewrite 重写功能一直没有深入学习,大多时候仅限于 RewriteRule规则的简单使用。这篇文章只是本人的一些测试与总结,有误也正常。
入门例子
<IfModule mod_rewrite.c>
RewriteEngine On
#条件1
RewriteCond %{REQUEST_FILENAME} !-f
#条件2
RewriteCond %{REQUEST_FILENAME} !-d
#规则1
RewriteRule ^test.html$ index.php [L]
#规则2
RewriteRule ^test.html$ test.php
</IfModule>
这几行重写规则,转为程序语言就是:
<?php
if(条件1 && 条件2){
规则1;
}else{
规则2;
}
如果,“规则 1”后面没有 [L],那么,转为程序语言就是:
<?php
if(条件1 && 条件2){
规则1;
}
规则2;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
以访问网址:http://127.0.0.2/test.html 为例:
(1)%{REQUEST_FILENAME} 是服务器变量,指“完整的文件路径名”,这里是“/test.html”。
(2)!-f 意思是“不是文件”;!-d 意思是“不是目录”。
(3)如果在http://127.0.0.2网站根目录下, 既不存在 test.html 这个文件, 同时 test.html 也不是文件夹, 那么就重定向到 index.php(规则1)。
(4)如果在http://127.0.0.2网站根目录下,真实存在 test.html 文件,或 test.html 是一个文件夹,那么就重定向到 test.php(规则 2)。
(5)[L] 表示,如果该条规则已经匹配了,就不再往下匹配
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
通过这个实例,可以总结出的知识点有:
(1)RewriteCond 是条件,连续多个条件之间,默认是 and;如果想要条件是或/or,则这么写:
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
(2)一条 RewriteRule 规则可以有多个条件(例子中:规则1 受限于条件1 和条件 2)。
(3)RewriteCond 条件(无论是一条,还是连续多条),只会作用于 它们后面的第一条 RewriteRule(例子中:条件1和条件2,只作用于规则1)。
(4)重定向匹配,按顺序由上到下。如果有多条 RewriteRule 匹配,则会以最后一条 RewriteRule 重定向(假设没有 [L])
(5)[L] 意思是最后一条 RewriteRule:如果被这条 RewriteRule 匹配,就不再往下匹配了。
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
附——服务器变量,引用方法是: %{NAME_OF_VARIABLE}
它们可以是下图列表的字符串之一(图片来自 apache手册)
常用的一些变量,它们所对应的值,大部分都可以通过 PHP 的 $_SERVER 获得。