.htaccessenv

.htaccess test if ENV is true or defined


I need to run a set of RewriteCond statements if an ENV is true or defined (if not defined, then presumed false). I've been trying to use:

RewriteCond %{ENV:IS_MOBILE} ^true$
RewriteCond ...

and (not sure if this is even valid)

RewriteCond %{ENV:IS_MOBILE} !=true
RewriteCond...

But neither seem to work. Any way I can do this?


Solution

  • Here's a real life sample that should help you to find the solution:

    If the host begins by "s" or "static" then create an environment variable called "STATIC" and set it to "1":

    RewriteCond %{HTTP_HOST} ^(s|static)\.mysite\.com$
    RewriteRule (.*) - [QSA,E=STATIC:1]
    

    Then what you may look for: if my hosts is "static" then if the files are considered "static" (img and so on) then stop:

    RewriteCond %{ENV:STATIC} 1
    RewriteRule (.*)\.(pdf|jpg|jpeg|gif|png|ico)$ - [L]
    

    Now if you want to be sure that the variable doesn't exist, just check if it's empty. Here's my rule just after the previous: it checks if the variable is not empty, and if so, there's an error = 404 (to simulate "not found"):

    RewriteCond %{ENV:STATIC} !^$
    RewriteRule (.*) /404.php [L]
    

    In your case if your env is not empty you suppose it's true:

    RewriteCond %{ENV:IS_MOBILE} !^$
    RewriteCond...
    

    In your case if your env is equals, exactly equals to the string true you suppose it's "true":

    RewriteCond %{ENV:IS_MOBILE} =true
    RewriteCond...
    

    Hope this helps.