Can I globally set $_SERVER['REDIRECT_URL'] before script execution?

Barry asked:

I’m in the process of migrating many sites from an old to a new server configuration. Each site is based on a similar (but sadly not identical) codebase, using mod_rewrite URLs.

  • Ubuntu 8.04 LTS => Ubuntu 12.04 LTS
  • Apache 2.22.8 => Apache 2.2.22
  • PHP 5.2 (FastCGI) => PHP 5.3 (PHP5-FPM)

Mostly working like a charm, but on the new config the $_SERVER[‘REDIRECT_URL’] is no longer set, and the code is failing due to a dependence on this global variable.

From what I understand, this variable gets set by Apache when a redirect occurs. Obviously this isn’t happening now, but I’m struggling to find the cause.

  • Is it the Apache upgrade, or (my guess) the switch from PHP FastCGI to PHP5-FPM?
  • How do I get this variable back?

I’d really rather not have to edit the code on each site, so I’ll set a global PHP auto_prepend if necessary, but ideally I’d like to fix the server configuration and have this set in the first place.

Potentially related: I now also have a couple of new $_SERVER variables, namely REDIRECT_SCRIPT_URL and REDIRECT_REDIRECT_SCRIPT_URL. These seem to have the correct data I want for the REDIRECT_URL, but also seem to indicate there’s two internal redirects occurring that weren’t before – Google searches for REDIRECT_REDIRECT_SCRIPT_URL only returns random var_dump outputs. Is SCRIPT_URL the new REDIRECT_URL?

Edit 1

Checking again REDIRECT_URL is (now) set, but always to ‘index.php’ (the mod_rewrite target) instead of the expected typed URL. I have resorted to a using PHP auto_prepend_file to manually set the needed variable.

I’m not sure how I missed it the first time round, but I’ve made several changes in the meantime so I suppose there’s an outside chance it wasn’t there. Apologies if this mislead anyone.

Edit 2

To address the mentions of ErrorDocument below, the mod_rewrite rule in use is:

RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]

The $_GET[‘url’] variable is set, so the rule must be working.

To be clear, at this stage I’ve gone with the auto_prepend_file workaround I mentioned initially.

My answer:

REDIRECT_URL is set only by the Apache web server, and only in certain circumstances. It is probably not something your code should be relying on. As far as I can tell, the best solution would be to fix the buggy PHP code; you can’t really force this to be always set in Apache.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.