Score:0

Apache IF condition based on custom HTTP header

cn flag

I have a RewriteRule directive in Apache that I would like to get applied only if a custom HTTP header is present.

What I have tried:

<If "%{HTTP:X-MyCustomHeader} in { 'present' }">
RewriteRule ^/$ /present.html [NC,R=301,L]
</If>
<Else>
RewriteRule ^/$ /absent.html [NC,R=301,L]
</Else>

This does not work at all, neither RewriteRule gets applied.

Alternative that I have tried:

<If "-n req_novary('X-MyCustomHeader')">

Does not work either.

I am testing with curl like

curl -is http://example.com/ -H X-MyCustomHeader:present

To validate that the header is present and seen, I tried using an env variable:

SetEnvIf  X-MyCustomHeader ^(present)$ MY_CUSTOM_VAR=$1
Header always set X-MyCustomHeader "### FOUND ###" env=MY_CUSTOM_VAR

This works as expected, and I get the FOUND in the response.

But again when I try to use the env variable in the IF statement, it will not get triggered, e.g.

<If "-n env('MY_CUSTOM_VAR')">

How can I do this with IF? And yes, I know there is a RewriteCond condition to check environment variables, but I need to use other directives as well, so I would like to switch them in an IF block.

According to the docs: https://httpd.apache.org/docs/trunk/en/expr.html#functions

When environment variables are looked up within an condition, it's important to consider how extremely early in request processing that this resolution occurs. As a guideline, any directive defined outside of virtual host context (directory, location, htaccess) is not likely to have yet had a chance to execute. SetEnvIf in virtual host scope is one directive that runs prior to this resolution.

So according to the docs, SetEnvIf variables should work, but they don't?

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.