利用.htaccess文件进行URL重写

2011年4月13日 · 13 years ago


今天折腾了好久这玩意儿,本地测试失败但是服务器端可以运行=_= 记下来权当备份吧。
一、配置服务器
首先,在apache里面的conf目录下找到httpd.conf文件,把
LoadModule rewrite_module modules/mod_rewrite.so
一行前面的#号去掉,打开rewrite_module模块。
然后,确认

<Directory "E:/xampp/htdocs">
AllowOverride All
Order allow,deny
Allow from all
</Directory>

二、准备.htaccess文件
在你的站点目录下,找到或者新建一个.htaccess文件,在win下命名会有点麻烦,自个儿慢慢折腾呗,用命令行进行重命名会比较简单。
然后在这个.htaccess文件里面,我们开始写入URL重命名规则。
比方说我们有
http://localhost/old.php?val=88
这样的URL,要改成
http://localshot/test/88
这样类型的URL,那么就这么写:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^test/([0-9]+)$ old.php?val=$1 [L]
</IfModule>

其中,
RewriteRule ^test/([0-9]+)$ old.php?val=$1 [L]
一句,“old.php?val=$1”是原来的URL,“^test/([0-9]+)$”是你想要改成的URL的正则表达式。
想要更深入研究rewrite模块,可以参考这个网址:初级URL重写指南 http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/rewrite_guide.html