htaccess If…Else always selects Else

前端 未结 4 1797
温柔的废话
温柔的废话 2021-02-12 21:59

I set an environment variable in httpd-vhosts.conf

SetEnv EARLY_VAR 1

I try setting special rules based on its value in

4条回答
  •  广开言路
    2021-02-12 22:45

    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
    

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


    EDIT:

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

    SetEnvIf Host ^ EARLY_VAR=5
    

    Then in your .htaccess you can use:

    
       SetEnv TEST_VAR if_branch
    
    
       SetEnv TEST_VAR else_branch
    
    

    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.

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

提交回复
热议问题