Using custom environment variables in .htaccess

13,326

Solution 1

This won't work, because mod_rewrite does not expand variables in test patterns. Consequently, your expression will attempt to match the regular expression ^%{foo}$, not ^value_of_foo$.

Additionally, the documentation for SetEnv also makes a special note about order-of-processing in relationship to mod_rewrite. This actually does come into play here, despite the rules being applied later in the request handling than the scenario they're describing there. If you don't perform a rewrite that causes an internal redirection before testing against the environment variable you set, it will be blank.

Assuming you set the variable correctly, a potential workaround is to do this, although I feel like it isn't foolproof:

RewriteCond %{HTTP_HOST}#%{ENV:foo} ^([^#]+)#\1$

Solution 2

Just set the environment using rewrite rules:

RewriteRule (.*) $1 [E=HOSTNAME_ENV:whatever.com]

This has also the advantage, that you are able to use RewriteCond.

Share:
13,326
shurik2533
Author by

shurik2533

Everything should be made as simple as possible, but no simpler. Albert Einstein

Updated on June 04, 2022

Comments

  • shurik2533
    shurik2533 almost 2 years

    I need something like this:

    SetEnv foo bar.baz
    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^%{foo}$
    RewriteRule ^(.*)$ http://www.foo/$1 [L]
    

    UPD:

    I have made as follows:

    SetEnv HOSTNAME_ENV testsite
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^%{ENV:HOSTNAME_ENV}
    RewriteRule ^(.*)$ http://www.%{ENV:HOSTNAME_ENV}/$1 [L,R=301]
    

    But it doesn't work. %{ENV:HOSTNAME_ENV} is not defined.