原文作者:DK Lynn(DK Lynn is a former instructor pilot and “rocket scientist” now living in New Zealand where he operates a small business developing and hosting web sites. )
================二道华丽的分割线(以下为本人译文)==========
学习 Apache mod_rewrite 13 例
Apache 以其极高的性价比让越来越多的公司组织选择它作为服务器。其中它有一个很有用的功能就是mod_rewrite模块,一个可将用户请求的URI根据特定规则转换的模块。
这篇文章将引领你学习rewrite 规则,正则表达,rewrite条件,以及提供了一系列的例子。
首先,我假设你已经懂得URI 重写对你网站的意义为前提,如果对这一方面你想了解得更多,这里我向你推荐 mod_rewrite: A Beginner’s Guide to URL Rewriting 这本书。你可以从书中找到关于这方面得更多信息。
测试服务器安装
一些服务器没有开启mod_rewrite模块(服务器默认关闭),你可以键入一行PHP代码来确定你的服务器是否已经开启mod_rewrite模块:
phpinfo();
在浏览器运行这段代码,找到Apache Modules section,如果mod_rewrite没有出现在其列表中,那么你就需要通知你的服务商开启mod_rewrite服务,或者..换另外一个好的服务商。大多数服务商都会开启mod_rewrite模块,所以你很容易找到。
mod_rewrite的魔力
简单举例:创建三个文件,分别命名为 test.html,test.php和.htaccess
test.html 输入:
<h1>This is the HTML file.</h1>
test.php输入:
<h1>This is the php file.</h1>
.htaccess输入:
RewriteEngine on
RewriteRule ^/?test\.html$ test.php [L]
将以上三个文件放test测试文件夹下,在浏览器录入: http://www.example.com/test/test.html
在浏览器中将 www.example.com替换成你自己的域名。如果运行结果显示“This is the PHP file”,那么运行成功,如果结果显示“This is the Html file”,那么肯定是哪里出了问题,请你再仔细检查下。
如果你测试成功,你是否发现了我们录入了test.html的文件名,确执行了test.php文件,是的,你已经初识了mod_rewrite的神奇。
mod_rewrite 正则表达式
现在我们可以重写URLs了!设想我们有一个显示城市信息的网站。根据URI选择城市:http://www.example.com/display.php?country=USA &state=California&city=San_Diego
这个URL太长并且对用户也不友好,我们更希望写成这样: http://www.example.com/USA/California/San_Diego
我们需要告诉Apache新的URL会根据一定的格式转化成这样,为了让display.php明白查询的字符,所以我们将用到正则表达式告诉mod_rewrite匹配我们的URLs。如果你对正则表达式不太熟悉,许多网站提供了优秀的教程供你学习。在本文的末尾,我也会列举出比较好的参考网址。如果你还是不能明白我所讲述的,那么我建议你看看后面链接中的前两篇。