---
title: "神奇的Apache Rewrite，程序员使用Rewrite的一些体会"
author: "renzhen"
date: "2012-02-15T11:42:39Z"
tags: ["Apache", "rewrite"]
categories: ["Web前端"]
slug: "apache-rewrite-rewrite"
draft: false
lastmod: "2012-02-15T11:46:01Z"
id: 1406948
url: "https://renzhen.iteye.com/blog/1406948"
---

最近在公司开发工作中，一些功能使用了Apache Rewrite技术，我对这方面是一个菜鸟，在实践中边学边做，得到了一些经验和网上资料，来分享一下。
   Apache是十分流行的开源软件，Apache Rewrite技术官方有着很详细的文档，关于Apache Rewrite技术是什么、如何使用等有着很详细的描述，下面有文档的中文版本：
   [http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/index.html](http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/index.html)
   
   在了解了Apache Rewrite技术之后，会发现使用这门技术需要用到正则表达式知识，正则表达式曾经评为程序员的七种武器之一，应用范围很广，如果你不会，那就看看下面的文档学习一下：
  [http://manual.phpv.net/regular_expression.html](http://manual.phpv.net/regular_expression.html)

   看完以上文档，理论上的知识就差不多够了，Apache Rewrite技术官方文档中还提供了很多实例和备注，基本上涵盖了Rewrite应用的方方面面。可以找一个和你实现功能差不多的的实例加以修改，又快又方便。
   [http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/rewrite_guide.html](http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/rewrite_guide.html)
   [http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/rewrite_guide_advanced.html](http://lamp.linux.gov.cn/Apache/ApacheMenu/rewrite/rewrite_guide_advanced.html)

   下面说一下本人使用Apache Rewrite技术一些东西。
    1.PHP实现伪静态规则

```php

RewriteEngine On
RewriteRule ^index\.php$ - [l]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) index.php/$1 [l]

```

   详细地址参看：[http://renzhen.iteye.com/blog/1329635](/blog/1329635)
    2. 根据二级域名分配不同的目录路径
    这个实例与下面的例子很像，详细可参看：
    [http://www.zzxj.net/blog/fxs_2008/archive/2009/01/20/6.html](http://www.zzxj.net/blog/fxs_2008/archive/2009/01/20/6.html) 
     其中有一个关键很重要，也很容易被忽视，就是<span style="color:red">在 httpd.conf 的最后，添加以下内容，</span> 一般Rewrite规则可以写在httpd.conf和.htaccess中，在一般情况下是通用的，可是在这里一定要写在httpd.conf中。原因后面会介绍。
    3. 使用Rewrite屏蔽某一类URL的访问，可以参看官方文档的相关实例。
    
    最后我想再说说Rewrite规则写在httpd.conf和.htaccess中的一个很重要的不同点，注定了有些规则只能在其中之一编写：

> [color=red]在 .htaccess 中设置的 rewrite rule，如果 REQUES_URI 变化，则apache会重新执行一遍 .htaccess 中的 rewrite rule，在 httpd.conf 中设置 rewriterule，则不会这个问题，是一锤子买卖[/color]。

    其他的不同点可以参看如下页面：[http://www.zzxj.net/blog/fxs_2008/archive/2009/01/18/1.html](http://www.zzxj.net/blog/fxs_2008/archive/2009/01/18/1.html)  这里就不赘述了。
    我的微博地址：<http://weibo.com/jameren>,欢迎大家关注。