Use SetEnvIf :
The internal environment variables set by this directive are set after most early request processing directives are run, such as access control and URI-to-filename mapping. If the environment variable you're setting is meant as input into this early phase of processing such as the
RewriteRuledirective, you should instead set the environment variable withSetEnvIf.