如何设置一个基本的mod_rewrite?

我听说你可以使用mod_rewrite清理你的URL,基本上我想这样做.php文件扩展名不显示在URL中。

例如,假设我在网站上有以下文件结构:

 /index.php /about.php /contact.php /css/main.css /img/animage.jpg /admin/index.php /admin/login.php /admin/admin.php 

我想用mod_rewrite进行如下的基本修改:

  • 当一个请求被发送到根目录即/about ,如果find一个目录叫做about ,那么它应该performance为一个名义上的目录(即从目录加载index.php)。
  • 如果没有find目录,它应该指向about.php
  • 如果请求一个.php文件,它应该301redirect到不带.php扩展名的.php名。
  • 只有那些直接在浏览器中直接查看的目录应该有这些URL改变(即根目录和admin目录),因此css和img应该保持它们的URL不变。

我怎样才能使用mod_rewrite进行这些更改?

在.htaccess文件中:

 RewriteEngine On RewriteBase / # Abort on directories, skip sub-requests RewriteCond %{REQUEST_FILENAME} -d RewriteRule .? - [L,NS] # Check if there is php file (add extension) RewriteCond %{REQUEST_URI}\.php -f RewriteRule (^.*) $1\.php [L] #Redirect explicit php requests (if file exist) RewriteCond %{REQUEST_FILENAME} -f # strange - REQUEST_URI always contains .php # have to parse whole request line # look for .php in URI (fields are space separated) but before '?' (query string) RewriteCond %{THE_REQUEST} ^[^\ ]+\ /[^\ \?]*\.php RewriteRule (.*)\.php$ $1 [NS,R=301] 

mod_rewrite是非常强大的:)