headermask image

header image

Drupal request_uri returns broken absolute URLs when served from an Apache VirtualHost

After upgrading my Drupal site to the latest point release (5.19), before transitioning to version 6, I discovered that the action parameter of all rendered forms were being prefixed a slash ‘/’. This in itself is reasonable since one would expect the REQUEST_URI server variable to return a relative URL. However, as I host several websites, Drupal runs inside its own VHost with URL rewriting to enable short URLs (without the ‘q=’ querystring). If I access Drupal directly via the web server’s address, which maps to the default VHost (this also happens to be Drupal), REQUEST_URI is relative. If I access it via the address externally visible on the web (http://spench.net/) then REQUEST_URI is absolute (i.e. prefixed with the protocol and domain).

The Druapl ‘request_uri’ function in includes/bootstrap.inc always adds a slash to the beginning of the server variable REQUEST_URI, which will break any absolute URLs.

The following modification (the strpos check) resolves this issue:

* Since $_SERVER['REQUEST_URI'] is only available on Apache, we
* generate an equivalent using other environment variables.
function request_uri() {
  if (isset($_SERVER['REQUEST_URI'])) {
    $uri = $_SERVER['REQUEST_URI'];
  else {
    if (isset($_SERVER['argv'])) {
      $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
    else {
      $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
  if (strpos($uri, '/') == 0)
    // Prevent multiple slashes to avoid cross site requests via the FAPI.
    $uri = '/'. ltrim($uri, '/');
  return $uri;

If you liked my post, feel free to subscribe to my rss feeds

Post a Comment

Your email is never published nor shared. Required fields are marked *