我在一些.htaccess示例中看到过这种情况

RewriteBase /

它的功能似乎有点类似于HTML的<base href="">。

我相信它会自动把它的值放在RewriteRule语句的开头(可能是没有斜杠的语句)?

我无法让它正常工作。我认为它的使用对于站点的可移植性非常方便,因为我经常有一个与生产服务器不同的开发服务器。我当前的方法让我从RewriteRule语句中删除部分内容。

谁能简单地给我解释一下如何实现它?

谢谢


当前回答

当我开发时,它在一个文件夹中的另一个域中。当我启动一个网站时,这个文件夹就不存在了。使用RewriteBase可以让我在两个环境中使用相同的.htaccess文件。

当生活:

RewriteBase /
# RewriteBase /dev_folder/

当开发:

# RewriteBase /
RewriteBase /dev_folder/

其他回答

用我自己的话说,在阅读了文档和实验之后:

您可以使用RewriteBase为您的重写提供一个基础。考虑一下这个

# invoke rewrite engine
    RewriteEngine On
    RewriteBase /~new/

# add trailing slash if missing
    rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]

这是我用来确保url有一个尾随斜杠的真实规则。这将会转换

http://www.example.com/~new/page

to

http://www.example.com/~new/page/

通过在那里设置RewriteBase,可以使相对路径脱离RewriteBase参数。

我相信这段摘自Apache文档的摘录,很好地补充了前面的答案:

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless either of the following conditions are true: The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias). The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). As previously mentioned, in other contexts, it is only useful to make your rule shorter. Moreover, also as previously mentioned, you can achieve the same thing by placing the htaccess file in the subdirectory.

当我开发时,它在一个文件夹中的另一个域中。当我启动一个网站时,这个文件夹就不存在了。使用RewriteBase可以让我在两个环境中使用相同的.htaccess文件。

当生活:

RewriteBase /
# RewriteBase /dev_folder/

当开发:

# RewriteBase /
RewriteBase /dev_folder/

我发现最清楚的解释不在当前的2.4 apache文档中,而是在2.0版本中。

#  /abc/def/.htaccess -- per-dir config file for directory /abc/def
#  Remember: /abc/def is the physical path of /xyz, i.e., the server
#            has a 'Alias /xyz /abc/def' directive e.g.

RewriteEngine On

#  let the server know that we were reached via /xyz and not
#  via the physical path prefix /abc/def
RewriteBase   /xyz

它是如何工作的?对于apache黑客来说,这个2.0文档继续提供了“关于内部处理步骤的详细信息”。

经验教训:虽然我们需要熟悉“当前”,但我们可以在历史中找到珍宝。

RewriteBase只在你只能把.htaccess放在你站点根目录的情况下有用。否则,你最好将不同的.htaccess文件放在站点的不同目录下,完全忽略RewriteBase指令。

最近,对于复杂的站点,我已经把它们去掉了,因为这使得从测试到实时的文件部署再复杂一步。