Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting PHP Document Root on webserver

Tags:

php

apache

ubuntu

Currently I have an Ubuntu 12.04 webserver running apache2. I have it setup to dynamically create subdomains by creating new folders under /sites/example.com/*/public /sites/example.com/www/public is reserved for my main root site.

This is working out, however I am unable to configure PHP's $_SERVER['DOCUMENT_ROOT'] to be dynamic to the newly created folder.

When I echo $_SERVER['DOCUMENT_ROOT'] I get /etc/apache2/htdocs which I assume is some sort of default path. I would like this to be: /sites/example.com/*/public instead

# Wildcards
<VirtualHost *:80>
    VirtualDocumentRoot /sites/example.com/%1/public
    ServerAdmin [email protected]
    ServerAlias *.example.com
</VirtualHost>

Curious why PHP doesn't pick up the the virtual document root setting above, I'm likely doing something wrong.

like image 266
mikevoermans Avatar asked Apr 28 '26 16:04

mikevoermans


1 Answers

Solution found at : http://joshbenner.me/blog/quick-tip-get-proper-document-root-when-using-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.

like image 86
Kevin Labécot Avatar answered Apr 30 '26 05:04

Kevin Labécot