RewriteBase是如何工作的-飞外

RewriteBase是如何工作的

对于Apache服务器来说,RewriteBase是一个很有用的服务器指令,它能让你很容易的一下更改大量的重写规则。
在这篇文章中,将用例子来介绍RewriteBase是如何工作的。

什么是RewriteBase

RewriteBase允许你在.htaccess文件中很容易的设置所有相对路径的开头。它的值被用于重写规则中涉及的目标路径。当然,他的值只适用于同一.htaccess文件中的重写规则。
如果在你的.htaccess文件中有很多重写规则,那么RewriteBase将很有用。比如,如果你想把所有的URL都迁移到新的目录,那么你只要修改RewriteBase的值即可,不需要修改任何从写规则。

举例说明RewriteBase是如何工作的

默认情况下,在.htaccess文件中使用的所有相对路径都是当前.htaccess文件所在的目录。比如,如果你的.htaccess文件在/folder文件夹下,那么在.htaccess文件中所有的相对路径都会以/folder开头。如果你有如下RewriteRule:

RewriteRule sub-dir1 sub-dir2

那么,Apache会把所有的/folder/sub-dir1请求重定向到/folder/sub-dir2。

RewriteRule允许你这么做。

下面是RewriteBase的语法:

RewriteBase /relative/path/

在上面的语句中设置的相对路径会被添加到每一个RewriteRule中的目标相对路径前。

下面看一个例子,假如你有如下RewriteBase规则:

RewriteBase /data/

在上一条指令的下面是如下RewriteRule规则:

RewriteRule product about

这条语句会把所有/product请求重定向到/data/about。

如果包含上述规则的.htaccess文件本身在/folder文件夹下,那么Apache会把所有/folder/product请求重定向到/data/about。

下面是包含上述规则的.htaccess文件的示例:

RewriteEngine On RewriteBase /data/ RewriteRule product about

在使用RewriteBase指令之前请先确保Apache服务器的mod_rewrite模块可用。

其他的例子

下面再看一个例子。

不使用RewriteBase的例子:

Options +FollowSymLinksRewriteEngine OnRewriteRule p index.php

包含上述规则的.htaccess文件在项目根目录的/test文件夹下,此时访问http://www.example.com/test/p链接会被重定向到http://www.example.com/test/index.php。
如果加上RewriteBase /,则会被重定向到http://www.example.com/index.php。

注意:

RewriteBase中的相对路径是相对于域名根目录的路径。RewriteRule中的重写字符串开头的/表示项目根目录,所以在使用RewriteBase的情况下最好不要在RewriteRule中的重写字符串前加/,加了/后,RewriteBase就不起作用了。

再看一个例子。

项目目录结构是:

|--项目根目录 |--test |----.htaccess |----index.php |--blog |--frontend |----index.php

/test/文件夹下的.htaccess中的规则为:

Options +FollowSymLinksRewriteEngine OnRewriteBase /blog/RewriteRule p frontend/index.php

访问http://www.example.com/test/p会被重定向到http://www.example.com/blog/frontend/index.php。

如果将RewriteRule改为:

RewriteRule p /frontend/index.php

会被重定向到http://www.example.com/frontend/index.php,出现404,RewriteBase /blog/没有起作用。

How Does RewriteBase Work With ExampleNotes on Creating Rewrite Rules