Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass REQUEST_URI from htaccess to PHP

I'm setting up a redirect URL where pass REQUEST_URI from .htaccess to PHP file.

Here is my files structure:

  • index.php
  • .htaccess
  • folder/index.php

If the URL is http://example.com/?something

I want to pass %{REQUEST_URI} full URL from .htaccess to folder/index.php and retrieve it with $_SERVER['REQUEST_URI'].

My folder/index.php:

echo $_SERVER['REQUEST_URI'];

.htaccess:

UPDATED:

Options +FollowSymLinks -MultiViews
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteCond %{REQUEST_URI} !/folder/index.php$
    RewriteRule .* /folder/index.php [L,NE]
</IfModule>

I expect to echo REQUEST_URI in PHP file but always give external server.

like image 703
Robert Avatar asked Dec 16 '25 19:12

Robert


1 Answers

I want to pass %{REQUEST_URI} full URL from .htaccess to folder/index.php and retrieve it with $_SERVER['REQUEST_URI'].

You can't actually do this (but I don't think this is what you are trying to do - or even want to do - anyway). To clarify...

The PHP superglobal $_SERVER['REQUEST_URI'] is populated by PHP and this cannot be overridden.

Whilst %{REQUEST_URI} (the Apache server variable) and $_SERVER['REQUEST_URI'] (the PHP superglobal) are similar, they reference different values:

  • %{REQUEST_URI} (Apache server variable) - references the URL-path only (no query string). The value is %-decoded. If the request is rewritten, then this is updated to contain the rewritten URL, not the URL of the initial request.

  • $_SERVER['REQUEST_URI'] (PHP superglobal) - Holds the initial URL-path and query string the user requested (not the rewritten URL). The value is not %-decoded.

If you really do want to reference the Apache server variable REQUEST_URI in PHP then you need to explicitly pass it (perhaps as an environment variable or query string) - but depending on when you "pass it", you could end up passing different values. And either way, this will not change the value of $_SERVER['REQUEST_URI'], which, as mentioned above, is controlled by PHP.

For example:

RewriteRule ^ - [E=APACHE_REQUEST_URI:%{REQUEST_URI}]

And reference this in PHP as getenv('APACHE_REQUEST_URI').


UPDATE:

By the sounds of it, you probably want something like the following instead:

RewriteCond %{QUERY_STRING} .
RewriteRule ^(index\.php)?$ folder/index.php [L,NE]

This internally rewrites any request for the document root, that contains a query string (everything after the ?) to /folder/index.php. When the query string is absent then index.php in the document root is served as normal.

Then, in /folder/index.php you simply access $_SERVER['QUERY_STRING'] to access the query string (the string to redirect to).

like image 185
DocRoot Avatar answered Dec 19 '25 12:12

DocRoot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!