Flow action set-header

A set-header action registers an HTTP response header to be sent to the client.

The value of the header can be set dynamically with the xpath attribute.

If you need to dynamically determine the name or even the number of headers to send, use the set-headers action instead.

If you need to send request headers to a source server, use the sources.xml file or requests action.

Syntax

  • name="..." the name of the header field to set (required)
  • value="..." the value of the header field
  • xpath="..." an XPath to compute the value of the header field (executed in the DC document)
  • replace="true|false" if true (the default value), all headers of the same name are removed and only the new header is set. Set-Cookie headers received from the backend are not replaceable

Usage

A simple use case is to send a fixed-value response header:

<flow>
  <default-request />
  <set-header name="X-Hello-From" value="Fred" />
  <parse />
</flow>

A dynamic value can be set with an XPath. The context document is the DC:

<set-header name="X-FIT-Version" xpath="server/fit-version" />

But you may access any other XML source with your XPath:

<set-header name="X-Mirror-UA" xpath="fit-document('fit://request/request')/request/header[@name='User-Agent']/@value" />

You can send multiple headers with the same name if replace is false. Note that multiple header fields with identical names (case insensitive) may be merged automatically by combining their values into a comma-separated list.

<set-header name="Cache-Control" value="max-age=3600" />
<set-header name="Cache-Control" value="private" replace="false" if=".." />

To unset all instances of an already registered header, overwrite it with no value:

<set-header name="Foo" value="Bar" />
<set-header name="Foo" value="" />

The status code of the response can be set with the Status header (that was introduced by CGI):

<flow>
  <if test="contains(request/url, 'old')">
    <set-header name="Status" value="410 Gone" />
    <dump in="fit://site/public/gone.html" />
  </if>
</flow>

A more complicated use case is passing HTTP Basic Auth. (Note that this is not the same as the auth action that terminates Basic Auth in FIT). Here, we check for the 401 response code with an if statement and then copy the WWW-Authenticate header.

For this to function, you also have to pass the Authorization request header to the corresponding backend in your sources.xml with <headers pass="Authorization" />. Of course, you could accomplish this with XSLT in a set-headers action, too.

<flow>
  <default-request />
  <set-header  if="fit-document('fit://request/content/main/response')/response/@status = 401" name="WWW-Authenticate" xpath="fit-document('fit://request/content/main/response')/response/header[@name='WWW-Authenticate']/@value" />
  <parse />
</flow>