and I'm all out of bubble gum…

There seems to be some discussion online, but no actual, y’know… documentation regarding these two server variables.

Apparently they were introduced in Apache 2.3, and they are wicked useful, it turns out. At least, wicked useful if what you want to do is figure out what the URL of a to a specific file on the server is, assuming that you have only its path and some other file’s URL.

What follows seems to be empirically correct, but I welcome corrections:

DOCUMENT_ROOT is the system file path to the root of the web server’s document directory (usually something like '/var/www/')

But, imagine that per-user web directories have been enabled on your server. That is, if my user is foo, then there is a directory /home/foo/public_html in which all of foo’s web documents are stored (and served from). This is (probably) outside of the main server document root directory. The URL of foo’s web files would be something like

And this is where our variables enter the story.

The Empirically-based Theory

CONTEXT_PREFIX is the portion of the REQUEST_URI that triggered the server to serve up a file outside of the document root. And CONTEXT_DOCUMENT_ROOT is the root directory that that particular CONTEXT_PREFIX is rooted at. Nota bene: conveniently CONTEXT_DOCUMENT_ROOT contains the path the document root for whichever context this particular script was accessed through (so it would be the same as DOCUMENT_ROOT within the server’s document root, while CONTEXT_PREFIX would be an empty string, since there is no context prefix within the server’s document root.

A file in a user web directory

Consider this extended example:

User foo has placed files in that user’s public_html directory. There are nested directories within that public_html directory, and we are accessing a file at this URL:

This file is stored at the following path in the file system:


Thus, a sampling of relevant server variables (presented in $_SERVER for the PHP users amongst us) would be:

REQUEST_URI is /~foo/dir1/dir2/dir3/file.php?paramA

SCRIPT_NAME is /~foo/dir1/dir2/dir3/file.php


CONTEXT_DOCUMENT_ROOT is /home/foo/public_html

A file within server’s document root

Alternatively, a similar example within the server’s document root:

is a URL that access a file at:


This results in the following values:

REQUEST_URI is /dir1/dir2/dir3/file.php?paramA

SCRIPT_NAME is /dir1/dir2/dir3/file.php

CONTEXT_PREFIX is (the empty string)


For giggles, I cooked up some code to generate the URL of particular directory based on this information. I used the following little snippet to do this in DataUtilities::overlap() in battis/data-utilities:

use Battis\DataUtilities;
$path = __FILE__;
$url = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ?
		'http://' :
	) .

March 30th, 2016

Posted In: How To

Tags: ,