18

I have a proxy that is injecting some headers but I want to modify it so it only sets the headers if they are not already present:

<Location /api>    
    RequestHeader set MY_HEADER "value"

    ProxyPass http://127.0.0.1:8000/api
    ProxypassReverse http://127.0.0.1:8000/api
</Location>

Is this possible?

Hobozilla
  • 324
  • 1
  • 3
  • 8

4 Answers4

12

In Apache 2.4.7, x86_64, Ubuntu 14.04 LTS

I have found that this works

RequestHeader setIfEmpty X-Forwarded-For "127.0.0.1"

works all day long. However if one tries to use a dynamic value,

RequestHeader setIfEmpty X-Forwarded-For "%{REMOTE_ADDR}e"

does not work. I have found that you need the help of mod_rewrite to harvest the value. My configuration now looks like this, and it works.

RewriteRule . - [E=noxff:%{REMOTE_ADDR}] RequestHeader setIfEmpty X-Forwarded-For "%{noxff}e"

I know it is stoopid, but it works.

Mauro Marzorati
  • 136
  • 1
  • 2
8

How about something like:

RequestHeader set X-My-Header "value" expr="req('X-My-Header')==''"

Consult http://httpd.apache.org/docs/current/expr.html for more info about the expr= syntax.

Edit: In Apache 2.2 you should be able to do this:

SetEnvIf X-My-Header "" no_my_header
RequestHeader set X-My-Header "value" env=no_my_header
MLu
  • 24,849
  • 5
  • 59
  • 86
5

Apache 2.4.7

Header setifempty Access-Control-Allow-Origin "*"

Apache 2.2.4 below

Header append Access-Control-Allow-Origin ""
Header edit Access-Control-Allow-Origin "^$" "*"
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
Kangur
  • 241
  • 3
  • 6
  • The solution for Apache 2.2.4 and below listed here `Header append Access-Control-Allow-Origin ""` `Header edit Access-Control-Allow-Origin "^$" "*"` may have a side effect of appending `, ` to a non-empty header value because it's how `append` action works. It's the case, at least, in Apache 2.4.6. – Artem Shafranov Feb 08 '21 at 17:00
2

The following should be an equivalent to RequestHeader setIfEmpty in Apache versions <=2.4.6 (where setIfEmpty action is not supported):

RequestHeader set MY_HEADER "value" "expr=-z %{req:MY_HEADER}"