htaccess If ... Else始终选择Else [英] htaccess If...Else always selects Else

查看:116
本文介绍了htaccess If ... Else始终选择Else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 httpd-vhosts.conf

SetEnv EARLY_VAR 1

我尝试根据 .htaccess

<If "%{ENV:EARLY_VAR} == '1'">
   SetEnv TEST_VAR  if_branch
</If>
<Else>
    SetEnv TEST_VAR  else_branch
</Else>

我希望 TEST_VAR 环境变量等于 if_branch 。在 PHP

I expect TEST_VAR environment var to equal if_branch. In PHP

var_dump(getenv('EARLY_VAR')); // string '1'
var_dump(getenv('TEST_VAR')); // string 'else_branch'

我也尝试设置 EARLY_VAR .htaccess 中的$ c>,都使用 SetEnv SetEnvIf 。总是执行 Else 分支。

I also tried setting EARLY_VAR in .htaccess above the If/Else, both using SetEnv and SetEnvIf. Always the Else branch is executed.

为什么?

Apache 2.4

推荐答案

不使用表达式,即 if / else 指令,您可以执行以下操作:

Without using expression i.e. if/else directives you can do this:

# set EARLY_VAR to 1
SetEnvIf Host ^ EARLY_VAR=1

# if EARLY_VAR is 1 then set TEST_VAR to if_branch
SetEnvIf EARLY_VAR ^1$ TEST_VAR=if_branch

# if EARLY_VAR is NOT 1 then set TEST_VAR to else_branch
SetEnvIf EARLY_VAR ^(?!1$) TEST_VAR=else_branch

这将起作用甚至使用较旧的Apache版本,即 <2.4

This will work with even older Apache versions i.e. <2.4

编辑:

在您的Apache配置或虚拟主机配置中,请执行以下变量初始化:

In your Apache config or vhost config have this variable initialization:

SetEnvIf Host ^ EARLY_VAR=5

然后在.htaccess中,您可以使用:

Then in your .htaccess you can use:

<If "env('EARLY_VAR') == '5'">
   SetEnv TEST_VAR if_branch
</If>
<Else>
   SetEnv TEST_VAR else_branch
</Else>

为什么在Apache / vhost配置中需要env变量声明,因为.htaccess在Apache / vhost之后加载在 if / else 表达式中无法评估在同一.htaccess中设置的config和env变量。

Reason why you need env variable declaration in Apache/vhost config because .htaccess is loaded after Apache/vhost config and env variables set in same .htaccess are not available for evaluation in if/else expressions.

请注意,使用 SetEnvIf 代替 SetEnv 对于使这些变量可用于 / else 表达式。

Also, note that it is important to use SetEnvIf instead of SetEnv to make these variables available to if/else expressions.

这篇关于htaccess If ... Else始终选择Else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆