Last Updated: February 25, 2016
·
9.199K
· ju

Passing Request URI into Request Header

This need stems from the need to pass the full request URI and query string into the application exactly as it was requested.

The application I needed it for was a legacy system that heavily used rewrites. Thus making it difficult to retrieve the actual requested URI without rebuilding the URI from the request variables, mainly because of the variety of rewrite rule "structures." With better planning and code structure this would would've been relatively easier to rebuild the url based on the request variables. But we aren't always that lucky when inheriting older applications.

Implementation

SetEnvIf Request_URI "^(.*)$" REQUEST_URI=$1
RequestHeader set X-Request-Uri "%{REQUEST_URI}e"
RewriteRule .* - [E=REQUEST_QUERY_STRING:%{QUERY_STRING}]
RequestHeader set X-Query-String "%{REQUEST_QUERY_STRING}e"

The above declarations require rewrite, setenvif, and headers apache2 modules to be enabled.

Usage

PHP

<?php

function getRequestedURI() {
  if ((!isset($_SERVER['X-Request-Uri']) || strlen($_SERVER['X-Request-Uri']) < 1) && isset($_SERVER['REQUEST_URI'])) {
    return $_SERVER['REQUEST_URI'];
  }

  $url = $_SERVER['X-Request-Uri'];
  if (isset($_SERVER['X-Query-String']) && strlen($_SERVER['X-Query-String'])) {
    $url .= '?' . $_SERVER['X-Query-String'];
  }

  return $url;
}

Coldfusion

<cffunction name="getRequestedURI">
  <cfset var resUrl = ''>
  <cfset var headers = GetHttpRequestData().headers />

  <cfif !structKeyExists(headers, 'X-Request-Uri') || len(headers['X-Request-Uri']) LT 1>
    <cfreturn cgi.server_name />
  </cfif>

  <cfset resUrl = headers['X-Request-Uri'] />
  <cfif structKeyExists(headers, 'X-Query-String') && len(headers['X-Query-String'])>
    <cfset resUrl += '?' & headers['X-Query-String'] />
  </cfif>

  <cfreturn resUrl />
</cffunction>