Search code examples
apache.htaccessmod-env

How to pass Apache environment variable to url in .htaccess


I am setting a apache environment variable through php function, apache_setenv.

apache_setenv("EXAMPLE_VAR", "Example Value");

But I am having problem accessing this variable inside .htaccess I am not able to use this env variable inside .htaccess in anyway. but I can access it through php getenv().

And problem is not only by setting variable through php I am unable to access env variable set by .htaccess itself.

I've tried

Suppose env variable to be www.domain.com.

RewriteEngine On
RewriteCond ^(.*)$ test.php?id=%{ENV:VARIABLE} [L]

&

RewriteEngine On
RewriteCond %{ENV:VARIABLE} ^www.(.+)
RewriteRule ^ test.php?id=%1 [L]

And similar other test to just verify that env variable are set and functioning.

Mod_env and mod_rewrite is on.


Solution

  • Variable set using SetEnv directives are not seen by mod_rewrite due to sequence of module loading by Apache. Use SetEnvIf instead like that:

    SetEnvIf Host ^ VAR=/foo/bin
    

    Then use it in mod_rewrite rules:

    RewriteEngine On
    
    RewriteCond %{ENV:VAR} =/foo/bin
    RewriteRule ^home/?$ /something [L,NC]