Setting a DYNAMIC Php $_SERVER value ($_SERVER['something']) using Apache .htaccess

.htaccess, apache, php

Solution

Depending on the information you require, you may be able to do this with a `RewriteRule`. For example:

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT} (.*)
RewriteRule (.*) - [E=RESOURCE_ROOT:%1]

will set the PHP var `$_SERVER['RESOURCE_ROOT']` or `$_SERVER['REDIRECT_RESOURCE_ROOT']` to your Apache Document Root. See the mod_rewrite manual for full details, but some combination of `%{DOCUMENT_ROOT}`, `%{PATH_INFO}` and `%{REQUEST_FILENAME}` may work for you.

I don't think it's possible for the `.htaccess` file to know what directory it resides in. So I think you'll need to use hardcoded paths inside your `.htaccess` file. As an example:

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT} (.*)
RewriteRule (.*) - [E=RESOURCE_ROOT:%1/module/unique_section/]

Problem

This is an exension to this question where we learn that we can set a `$_SERVER` var using `SetEnv`. The next question is: Is there a way to use SetEnv essentially like this: /var/www/www.example.com/module/unique_section/.htaccess: ``` SetEnv RESOURCE_ROOT %{DIRECTORY} ``` /var/www/www.example.com/module/unique_section/some/path/file.php ``` <?php echo $_SERVER['RESOURCE_ROOT']; ?> ``` Output: `/var/www/www.example.com/module/unique_section/`

Original source

Related problems