.htaccess test if ENV is true or defined
Asked Answered
S

2

11

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?

Straightaway answered 14/11, 2011 at 9:55 Comment(0)
F
12

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.

Freemasonry answered 14/11, 2011 at 15:25 Comment(2)
This basically pointed me to my solution but it should be noted that in some cases, Apache will strip any none standard environment variables so you will also have to define your ENV inside the virtual host.Straightaway
Ooops I'm only working in vhost environment so that's not a problem but you're right to notice this. Thanks again.Freemasonry
K
-2

I think you need to wrap the code using IfDefine first

<IfDefine %{ENV:IS_MOBILE}>
     RewriteCond %{ENV:IS_MOBILE} true
</IfDefine>
Kaiser answered 10/12, 2018 at 17:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.