mod_rewrite最简单的知识

来源:互联网 发布:中国海关进出口数据 编辑:程序博客网 时间:2024/05/16 17:34
开启Apache 的mod_rewrite功能:
在Apahce的配置文件httpd.conf中把#LoadModule rewrite_module modules/mod_rewrite.so
前的#去掉,改为LoadModule rewrite_module modules/mod_rewrite.so
在httpd.conf中找到下面这段

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

将AllowOverride None 改成 AllowOverride ALL

这样Apache的mod_rewrite就开启了。

简单使用mod_write。
该功能的使用:一种是将转向规则写在httpd.conf中,这样效率比较高,但缺乏灵活性;
另一种是写在.htaccess文件中,将该文件放到需要运用该重写规则的网站目录的根目录。
比如网站结构
+DocumentRoot
|---News
|---BBS
|---Blog
以上结构中我只希望在新闻模块运用mod_write则只需将.htaccess
文件放到 /News目录下,则该目录下的所有请求都会去和.htaacess中的地址重写规则匹配。.htaccess虽然灵活但确带来性能上的缺失。

重写规则样例(其中的正则表达式就不在此叙述了):
RewriteEngine On
RewriteRule ^index(.*)$ /test.php [L]
RewriteRule ^index_([0-9]+).html$ getnews.php?id=$1 [L]

第一句RewriteEngine On一定不能少,否则该文件将不起任何作用。
第二句RewriteRule表示规则开始,具体为^index(.*)$ 将对 index,cgi (cgi表示html,php,。。等)的请求让test.php来处理,但地址栏上仍然写的是 index.cgi。[L]表示该规则结束
第二句 ^index_([0-9]+).html 表示 index_(0~9的任何数字任何组合).html, 就等于可以是 index_1.html
index_94.html , index_4565.html ...任何的形式
以 index_94.html 为例:
对index_94.html 的请求 将会交给 getnews.php?id=94来请求,可见 $1就代表参数([0-9]+)。

这个例子演变后可以完成大部分的请求:

RewriteRule ^new
原创粉丝点击