在Web服务器上设置PHP文档根目录

3

我目前有一个运行着Apache2的Ubuntu 12.04 Web服务器。我已经设置它来通过在/sites/example.com/*/public下创建新文件夹来动态创建子域名,其中/sites/example.com/www/public为我的主要根站点保留。

这个方法很有效,但是我无法将PHP的$_SERVER['DOCUMENT_ROOT']配置为动态创建的新文件夹。

当我输出$_SERVER['DOCUMENT_ROOT']时,我得到的是/etc/apache2/htdocs,我认为这是某种默认路径。我希望它变成/sites/example.com/*/public。

# Wildcards
<VirtualHost *:80>
    VirtualDocumentRoot /sites/example.com/%1/public
    ServerAdmin mike@example.com
    ServerAlias *.example.com
</VirtualHost>

我很好奇为什么PHP不能获取上述虚拟文档根目录设置,可能是我做错了什么。


你确定文件是从 /sites/example.com/*/public 正确的 DocumentRoot 中服务出来的吗?你正在测试哪个 PHP 文件的路径,以及你使用什么 Host 来获取它? - Bendoh
1
是的,其余的PHP代码都按照我的预期执行。看起来这个变量在每个主机上都可能不同。这似乎可以解决问题,但我不确定它是否是最佳解决方案(http://joshbenner.me/blog/quick-tip-get-proper-document-root-when-using-mod-vhost-alias/)。 - mikevoermans
2个回答

7

解决方案位于:http://joshbenner.me/blog/quick-tip-get-proper-document-root-when-using-mod-vhost-alias/

该链接提供了一个关于使用mod_vhost_alias时如何获取正确文档根目录的快速提示。

The Apache module mod_vhost_alias and its VirtualDocumentRoot directive can really be a great time saver for local development (some googling will explain why in more deapth). Basically, my local dev is set up so that I just have to create a directory in my aliases directory, and I just then navigate my browser to a URL matching the name of that new directory, and apache knows exactly what to serve automagically.

However, there are a few evil gotchas when using mod_vhost_alias, one of which is that the PHP global $_SERVER['DOCUMENT_ROOT'] remains set to the apache default DOCUMENT_ROOT environment variable rather than being re-assigned to the document root activated by the VirtualDocumentRoot directive for the current URL. This can cause some PHP applications (that are too trusting) to die for one reason or another.

I found a great solution to this in the related apache bug report: Simply add the following line to your apache configuration inside the VirtualDocumentRoot vhost definition:

php_admin_value auto_prepend_file /path/setdocroot.php

Then, create the referenced PHP file, and put set this as its contents:

<?php $_SERVER['DOCUMENT_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['SCRIPT_FILENAME']); ?>

Now, every page load has this file executed, which properly sets DOCUMENT_ROOT.


我做到了这一点,并设置了 php_admin_value auto_prepend_file /sites/example.com/_setdocroot.php,它实现了我的需求。 - mikevoermans

1

显然,Apache 2.4 已经解决了这个问题。不幸的是,Ubuntu 12.04 仍在运行Apache 2.2。

话虽如此,Ubuntu 14.04(下一个LTS版本)现在已经发布,do-release-upgrade应该已经可以用于从12.04升级到14.04,因为14.04已经 上周 发布了第一个补丁版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接