128

I have a Linux environment and I have a PHP Web Application that conditionally runs based on environment variables using getenv in PHP. I need to know how these environment variables need to be set for the application to work correctly. I am not sure how to set this up on Apache.

Also, I need to be able to configure separate environment variables for each domain separately.

Please advice on how can I achieve this.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
Abishek
  • 11,191
  • 19
  • 72
  • 111

4 Answers4

188

Something along the lines:

<VirtualHost hostname:80>
   ...
   SetEnv VARIABLE_NAME variable_value
   ...
</VirtualHost>
wroniasty
  • 7,884
  • 2
  • 32
  • 24
  • 4
    was not in my $_ENV array, for retreiving value see: http://stackoverflow.com/questions/2378871/set-application-env-via-virtual-host-config-and-read-this-in-php – i_a Aug 04 '15 at 22:26
  • 6
    @i_a you can access the value in PHP with `getenv('VARIABLE_NAME')` – BeetleJuice Jul 08 '16 at 00:34
  • in xampp on windows the file will be C:\xampp\apache\conf\extra\httpd-vhosts.conf – Dung Apr 03 '17 at 19:09
  • 1
    @i_a On my machine the value can also be found in the `$_SERVER` variable. – robsch Feb 19 '20 at 11:20
  • Also you can use you `Include` or `IncludeOptional` if you don't want to change vhost.conf – Joe Bobson Jul 22 '20 at 18:29
36

You can also do this in a .htaccess file assuming they are enabled on the website.

SetEnv KOHANA_ENV production

Would be all you need to add to a .htaccess to add the environment variable

paquettg
  • 1,364
  • 1
  • 9
  • 16
  • is this any different from using a .env file such as the way laravel does this? Does this make it any way less secure? I ask this because I'm building the same backend structure with multiple frameworks (laravel, express, django, etc.) and some developers of those other languages say its' not appropriate to use .env and that the "server config" should be used instead, or doing it through the command line, heroku style – OzzyTheGiant Mar 13 '19 at 16:29
18

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in /etc/apache2/envvars location.

Just like this below line, you need to add an extra line in /etc/apache2/envvars

export MY_ENV_NAME=myEnvValue

ikhvjs
  • 5,316
  • 2
  • 13
  • 36
Sachin Raghav
  • 452
  • 5
  • 14
10

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
danday74
  • 52,471
  • 49
  • 232
  • 283
  • Not sure why in MacOSX's apache, the `DocumentRoot ${mydocroot}` simply write it as a string vs evaluating it and place it in the vhost – Ricky Levi Oct 26 '22 at 10:42