Skip to content

Let Apache environment variables survive an internal redirect

  • by

Recently I discovered that Apache can use environment variables. This can be very useful for some situations. In my case I want to determine if a webpage was visited via a redirect or directly via de URL. I figured this would be possible by setting an environment variable on the redirect, so I could filter it in PHP. However my environment variables wouldn’t reach the webpage after an internal redirect set in an .htaccess file.

It turns out that the the environment variables are prefixed by REDIRECT_ when an internal redirect happens as described on the Advanced Techniques with mod_rewrite page. It took me a while to figure out this important piece of information. However in my case the RewriteRule was the final one, and the URL wasn’t rewritten afterwards. So why was the final redirect happening?

When setting a RewriteRule inside an .htaccess file, the PT flag is implied. This means that every URL is passed back to the URL mapper even if there are no changes to occur. Therefore the environment variables are all prefixed with REDIRECT_. As mentioned in PT flags section: “The only way to circumvent that is to rewrite to -.”

So if you want your environment variable to survive internal redirects (and not be prefixed by REDIRECT_), by rewriting to – as a final rule, we can pass the environment variable to the final page without it being prefixed.

RewriteEngine On
RewriteRule !foo\.php foo.php [E=SECRET_KEY:value]

RewriteCond %{ENV:REDIRECT_SECRET_KEY} value
RewriteRule ^ - [E=SECRET_KEY:value]

We check if the redirected variable is present, and if so we pass it on again to the final page without a internal redirect this time.

Maybe this trick can help you out as well!

Leave a Reply

Your email address will not be published. Required fields are marked *