Apache get environment variable value

apache-2.4environment-variables

I would like to get the value of a environment variable and assign it to another variable in Apache.

For example, get the value of $_SERVER['REMOTE_ADDR'] assign it to $_SERVER['USER-IP'] and override $_SERVER['REMOTE_ADDR'] to 127.0.0.1

I am stuck on getting the value of REMOTE_ADDR

<IfDefine !USER-IP>
  SetEnv USER-IP %{REMOTE_ADDR}
  SetEnv REMOTE_ADDR '127.0.0.1'
</IfDefine>

Best Answer

Looking at the docs, the $_SERVER['REMOTE_ADDR'] var is not strictly an environment variable, but a cgi request meta-variable provided by the web server to the cgi context; http://www.faqs.org/rfcs/rfc3875.html

Meta-variables contain data about the request passed from the server to the script

  meta-variable-name = "AUTH_TYPE" | "CONTENT_LENGTH" |
                       "CONTENT_TYPE" | "GATEWAY_INTERFACE" |
                       "PATH_INFO" | "PATH_TRANSLATED" |
                       "QUERY_STRING" | "REMOTE_ADDR" |
                       "REMOTE_HOST" | "REMOTE_IDENT" |
                       "REMOTE_USER" | "REQUEST_METHOD" |
                       "SCRIPT_NAME" | "SERVER_NAME" |
                       "SERVER_PORT" | "SERVER_PROTOCOL" |
                       "SERVER_SOFTWARE" | scheme |

The apache docs indicate that these variables cannot be overriden using the standard SetEnvstyle directives

Some Caveats

It is not possible to override or change the standard CGI variables using the environment manipulation directives.
https://httpd.apache.org/docs/2.4/env.html#setting

So I think it's unlikely you can set those values easily from apache conf

Setting environment variables

(from existing server variables)

<Directory /var/www/server111>
    Order allow,deny
    Allow from all

    # This syntax works, as you can see from the image below...
    RewriteEngine On
    RewriteRule .* - [E=USER-IP:%{REMOTE_ADDR}]

    # none of these syntax seem to work
    SetEnv USERIP %{REMOTE_ADDR}
    SetEnv USERIP2 blah
    SetEnv USERIP3 ${REMOTE_ADDR}
    SetEnv USERIP6 %{ENV:REMOTE_ADDR}
</Directory> 

enter image description here