How to Set Apache Environment Variables
This article provides a quick overview and practical guide on how to
define, manage, and use environment variables within the Apache HTTP
Server configuration. You will learn about the primary directives
required, such as SetEnv and PassEnv, and see
real-world examples of how to apply them within your server
configuration or .htaccess files to enhance your web
application’s security and flexibility.
The SetEnv Directive
The most common way to define an environment variable directly inside
Apache is by using the SetEnv directive. This directive
takes a variable name and a value as arguments, making the variable
accessible to server modules and external applications like PHP or
Python scripts.
SetEnv DATABASE_USER "db_admin"
SetEnv APP_STATUS "production"You can place these lines inside your main server configuration file
(e.g., httpdocs.conf or apache2.conf), within
a specific VirtualHost block, or inside a local
.htaccess file.
The PassEnv Directive
If a variable is already set in your operating system’s environment
before Apache starts, you can pass it into Apache’s context using the
PassEnv directive. This is highly useful for containerized
environments like Docker, where secrets are often injected at the system
level.
PassEnv PATH
PassEnv SYSTEM_SECRET_KEYConditional Variables with SetEnvIf
Sometimes you only want to set a variable under specific conditions,
such as matching a particular request header or client IP address. The
SetEnvIf directive allows you to use regular expressions to
conditionally apply environment variables.
SetEnvIf Request_URI "\.(jpg|jpeg|png|gif)$" IS_IMAGE=true
SetEnvIf Remote_Addr "192\.168\." IS_LOCAL_USER=trueVerifying and Using Your Variables
Once defined, these variables are passed to CGI scripts, SSI pages,
and PHP via the $_SERVER superglobal array. For example, in
PHP, you can easily retrieve your Apache environment variable using the
standard getenv() function:
$db_user = getenv('DATABASE_USER');