views:

2228

answers:

3

Hi, suppose we have the following PHP page "index.php":

<?
if (!isset($_GET['req'])) $_GET['req'] = "null";
echo $_SERVER['REQUEST_URI'] . "<br>" . $_GET['req'];
?>

and the following ".htaccess" file:

RewriteRule ^2.php$ index.php?req=%{REQUEST_URI}
RewriteRule ^1.php$ 2.php

Now, let's access "index.php". We get this:

/index.php
null

That's cool. Let's access "2.php". We get this:

/2.php
/2.php

That's cool too. But now let's have a look at "1.php":

/1.php
/2.php

So... we ask for "1.php", it silently redirects to "2.php" which silently redirects to "index.php?req=%{REQUEST_URI}", but here the "%{REQUEST_URI}" seems to be "2.php" (the page we're looking for after the first redirection) and the $_SERVER['REQUEST_URI'] is "1.php" (the original request).

Shouldn't these variables be equal? This gave me a lot of headaches today as I was trying to do a redirection based only on the original request. Is there any variable I can use in ".htaccess" that will tell me the original request even after a redirection?

Thanks in advance and I hope I've made myself clear. It's my first post here :)

+4  A: 

I'm not sure whether it will meet your needs, but try looking at REDIRECT_REQUEST_URI first, then if it's not there, REQUEST_URI. You mention in your comment to Gumbo's answer that what you're truly looking for is the original URI; REDIRECT_* versions of server variables are how Apache tries to make that sort of thing available.

chaos
Unfortunately, adding the [PT] modifier didn't make any difference.
bilygates
+2  A: 

Just change the order of the rules and it works:

RewriteRule ^1\.php$ 2.php
RewriteRule ^2\.php$ index.php?req=%{REQUEST_URI}

Or use just one rule:

RewriteRule ^(1|2)\.php$ index.php?req=%{REQUEST_URI}
Gumbo
Yes, I guess that works for the example I have posted, although I was rather looking for a variable that can tell me the original request even after one or more redirects.
bilygates
+1  A: 

Well I guess I solved the problem. I used the %{THE_REQUEST} variable which basically contains something like this: "GET /123.php HTTP/1.1". It remains the same even after a redirection. Thanks everyone for your help! :)

bilygates
Why don’t you simply use `$_SERVER['REQUEST_URI']`?
Gumbo
I need to use the variable in .htaccess, not in PHP. As I mentioned in my first post, %{REQUEST_URI} doesn't contain the original request after a redirection/rewrite.
bilygates