0

I am using Apache 2.4.6

I wanted to check if a custom header X-CUSTOM-HEADER is present in the request, if yes then set the same header and same value to the response. If the header is not present in the request then set the response header with a random value.

I am not able to read and set the same value from request Header to response header.

#******* THIS CODE DOES NOT WORK ********
Header set X-CUSTOM-HEADER %{req:X-CUSTOM-HEADER}e "expr=%{req:X-CUSTOM-HEADER} != ''"

I have also tried 'SetEnv' and 'Define' to read and set the header value to a variable and then use the variable while setting the response header, but that also did not worked.

In case the header is not presetn, I am using the mmod_unique_id module to set unique value.

****** THIS CODE WORKS *******
Header set X-CUSTOM-HEADER %{UNIQUE_ID}e "expr=%{req:X-CUSTOM-HEADER} == ''"

1 Answer 1

0

The variable %{req:X-CUSTOM-HEADER}e is not a normal environment variable. It's actually using a special function[1] that's only available in an ap_expr expression. If you want to access the request headers outside of an ap_expr, you have to be a little more creative. Depending on the handler for the file type you are accessing, it might be available in environment variables with the HTTP_ prefix, followed by the "normalized" name of the header (dashes to underscores, all caps).

For example:

Header set X-CUSTOM-HEADER %{HTTP_X_CUSTOM_HEADER}e "expr=%{req:X-CUSTOM-HEADER} != ''"
Header set X-CUSTOM-HEADER %{UNIQUE_ID}e "expr=%{req:X-CUSTOM-HEADER} == ''"

This works when accessing a PHP file through PHP-FPM (since FastCGI sets those variables), but not a simple HTML file. For that situation, you can get a little more creative with mod_rewrite, as it natively supports checking HTTP headers using RewriteCond.

# This grabs the existing header, if set, and creates the environment variable
RewriteCond %{HTTP:X-CUSTOM-HEADER} (.+)
RewriteRule . - [env=HTTP_X_CUSTOM_HEADER:%1]

Header set X-CUSTOM-HEADER "%{HTTP_X_CUSTOM_HEADER}e" env=HTTP_X_CUSTOM_HEADER
Header set X-CUSTOM-HEADER %{UNIQUE_ID}e env=!HTTP_X_CUSTOM_HEADER

[1] https://httpd.apache.org/docs/2.4/expr.html#vars

[2] https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewritecond

1
  • Perfect... worked as expected! Thanks for your response. Commented Mar 25 at 12:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .