mod_rewrite模块的归纳总结
1、mod_rewrite模块的优点以下URL范例:
很不友好的URL:
1
http://example.com/user.php?id=5412
比较友好的URL:
1
http://example.com/user/4512/
非常友好的URL:
1
http://example.com/user/joe/
以上可由mod_rewrite实行URL转换
2、mod_rewrite模块的启用
1)修改apache主配置文件
vim编辑/etc/httpd/conf/httpd.conf
去掉以下行的注释:
1
LoadModule rewrite_module modules/mod_rewrite.so
2)重启服务
1
/etc/init.d/httpd restart
3、检查mod_rewrite模块是否启用
1)在Apache的配置文件中的“DocumentRoot”定义的目录通过vim编辑index.php
并加入如下内容:
1
<?php phpinfo(); ?>
2)访问主机的http服务会看到如下显示
3)或者用shell命令测试
1
apachectl -t -D DUMP_MODULES | grep rewrite
显示如下:
1
rewrite_module (shared)
3、mod_rewrite模块的全局配置文件
在Apache的配置文件中的“DocumentRoot”定义的目录下有一个名字为“.htaccess”的隐藏文件
1)查看命令
1
ls -la
显示如下:
1
-rwxrwx---.1 root apache 412 Dec2 15:37 .htaccess
2)“.htaccess”的变量前缀
在Apache的配置文件中的“DocumentRoot”定义的目录下
vim编辑test.php
加入如下内容:
1
2
3
<?php
echo $_SERVER['REQUEST_URI']
?>
页面执行输出:
1
/test.php
1
2
mkdir test
mv test.php test
页面执行输出:
1
/test/test.php
以上变量“REQUEST_URI”如果写入".htaccess"的出来的结果最前面的"/"都会被去掉。
3、mod_rewrite模块的正则表达式
3、mod_rewrite模块的范例
1
2
3
4
5
6
7
# Enable Rewriting
RewriteEngine on
# Rewrite user URLs
# Input:user/NAME/
# Output: user.php?id=NAME
RewriteRule ^user/(w+)/?$ user.php?id=$1
范例解析:
1
2
3
4
5
6
7
8
9
10
11
12
13
T规则:
RewriteRule ^user/(w+)/?$ user.php?id=$1
匹配模式:
^ 输入的开头
user/ 以“user/“开始的请求地址
(w+) 提取所有的字母,并将提取的结果传给$1
/? 可选的斜线 "/"
$ 输入结束
替换为:
user.php?id= 要用到的字符串.
$1 上面第一个提取到的字符串。
页:
[1]