Jamgold
Jamgold

Reputation: 1744

How to access regex back reference in Apache 2.4 if statement

I am trying to process a certain request header injected and strip out a particular value and set a new request header with that value.

The existing header looks like this and I want to get to the actual clientip

OSGD-Signed-Data="clientip=x.x.x.x;gateway-features=routing-token-nocert,gateway-http-upgrade;timestamp=1532711365214"

So I created an <If> statement with a regex

<If "%{http:OSGD-Signed-Data} =~ /clientip=([^;]*);/"> RequestHeader set X-Client-IP $0 </If>

which matches, but I can't figure out how to use the back reference to set my new header

Upvotes: 0

Views: 1646

Answers (1)

piit79
piit79

Reputation: 1305

This doesn't seem to be possible directly. The Apache 2.4 documentation for expr states:

The strings $0 ... $9 allow to reference the capture groups from a previously executed, successfully matching regular expressions. They can normally only be used in the same expression as the matching regex, but some modules allow special uses.

I solved this by using SetEnvIf within the <If>. Your config would look something like this:

<If "%{http:OSGD-Signed-Data} =~ /clientip=([^;]*);/">
    SetEnvIf OSGD-Signed-Data clientip=([^;]*); CLIENT_IP=$1
    RequestHeader set X-Client-IP %{CLIENT_IP}e
</If>

This has the drawback that the regex needs to be specified twice (and is therefore also evaluated twice) - once in the <If> expression and again in SetEnvIf.

Upvotes: 2

Related Questions