php.htaccessmod-rewriteurl-rewritingrequest-uri

How to use RewriteRule such that $_SERVER['REQUEST_URI'] is modified too for PHP?


With this .htaccess:

RewriteEngine On
RewriteRule foo/(.*) /foo-$1         # here I tried [L], [PT], [C], etc.
RewriteRule . index.php [L]

I've tried all possible flags for the first RewriteRule, but always, this PHP code:

<?php echo $_SERVER['REQUEST_URI']; ?>

always echoes /foo/bar instead of /foo-bar, when accessing http://example.com/foo/bar. Why?

How to have Apache's RewriteEngine also modify the REQUEST_URI that will be seen by PHP?

Note: I don't want [R] because a redirection would generate a new browser request, and change the URL displayed in the URL bar, which I don't want.

See also RewriteRule when the substitution string is not a file path but an URL which should be processed by next rules.


Solution

  • After further research, it seems that PHP will always see the original URL in $_SERVER['REQUEST_URI'] and not the target of the RewriteRule. (authoritative source needed here).

    By the way, the target of a RewriteRule is usually a file that will process the request, except if we use a [R] redirection flag, then in this case the browser will do a new request to the new URL (and the browser URL bar changes).