I would like to combine the following SetEnvIF configuration into single line. Is it possible to do so?

SetEnvIF X-Forwarded-For ^(91\.148\.158\.226|77\.70\.95\.131) TRUSTED_IPS
SetEnvIf X-Real-IP ^(91\.148\.158\.226|77\.70\.95\.131) TRUSTED_IPS
  • Are you running out of newlines? SetEnvIf and SetEnvIfNoCase syntax SetEnvIf attribute regex [!]env-variable[=value] [[!]env-variable[=value]] ... doesn't allow you to combine attributes. However you can set the same variable in as many SetEnIfdirectives as you want and it will work exactly the same way in allow/deny. Having separated lines also increases readability. I just can't figure out the purpose for this request. – Esa Jokinen Mar 28 '17 at 10:54
  • Hi @EsaJokinen Purpose is to avoid having the same IPs on two lines. – Radoslav Stefanov Mar 28 '17 at 11:42

As per the docs, the attribute of the directive actually accepts a regex, but no example is given in its section. Rather one can be seen under Environment Variables > Examples. In your case it would be:

SetEnvIF ^X-(?:Forwarded-For|Real-IP)$ ^(91\.148\.158\.226|77\.70\.95\.131) TRUSTED_IPS

As this wouldn't be a problem with just one pair of IP addresses I assume you have many IP addresses you would like to go through without adding them all on two separate lines.

As SetEnvIf Directive only has one correct syntax,

SetEnvIf attribute regex [!]env-variable[=value] [[!]env-variable[=value]] ...

it is not possible to add two attributes on the same line. Therefore it is not possible to combine the two lines as you suggested, i.e. it is not possible to shorten a configuration of just these two lines. However, it is still possible to shorten configuration, if you have a longer list of IP addresses.

Since you have Apache 2.4, you could use mod_macro by first creating a macro like this:

<Macro AddTrustedIP $ip>
    SetEnvIF X-Forwarded-For ^($ip) TRUSTED_IPS
    SetEnvIf X-Real-IP ^($ip) TRUSTED_IPS

And then use it like this for every IP:

Use AddTrustedIP 91\.148\.158\.226
Use AddTrustedIP 77\.70\.95\.131

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.