Apache Custom Header with an environment variable

I try to set a custom HTTP Header with an environment variable** with Apache server 2.4.6 and headers_module.

I work inside a HTTP VHost on port 80.

Everything work as expected with basic example like:

Header set MyHeader "%D %t"

I have read the Apache Documentation of mod_headers : https://httpd.apache.org/docs/2.4/en/mod/mod_headers.html#header

It is said that one can access environment variable using %{ENVVARNAME}e

(with ENVVARNAME the name of the ENV variable)

I also read other post but no real working answer: Apache set custom header with an evironment variable

But my problem is to add a header than identify my Apache Server like the HOSTNAME environment value

  1. I tried this

Header Set X-Serv %{HOSTNAME}e

No success : always display X-Serv:{null} instead of the value

  1. I also tried :

SetEnv myvar ${HOSTNAME} Header set X-Serv %{myvar}e

No success : it displays in my HTTP Headers : X-Serv: %{myvar}e

I also tried some other various combinations:

Please note: My HOSTNAME environment variable exists and it display in 'env' command with the apache user owning the httpd process

Any idea?


You have to declare which system environment variables you want to be usable with the PassEnv directive

A working example would be:

PassEnv HOSTNAME
Header Set X-Serv %{HOSTNAME}e

Found a way to get it working:

  • Ensure module is activated (mod_headers) or activate if necessary

    a2enmod headers
    
  • in /etc/apache2/envvars add

    export HOSTNAME=`uname -n`
    
  • in <VirtualHost> clause

    Header set apachehost ${HOSTNAME}
    
  • Restart or reload httpd service

    service apache2 restart
    

1.Ensure module is activated (mod_headers) or activate if necessary

a2enmod headers

2.in /etc/apache2/envvars add

export HOSTNAME1='uname -n' or 'hostname'

3.in <VirtualHost _default:443> clause

PassEnv HOSTNAME1

Header set X-Server "%{HOSTNAME1}e"

4.Restart or reload httpd service

service apache2 restart