Nginx – How to set server specific ENV values in Nginx

environment-variablesnginxvirtualhostweb-server

I am starting a project that uses environment variables to set the database connection and a couple other things. (They didn't want to use configuration files since people are careless and overwrite them).

Anyway, I am using nginx and while it supports env – it doesn't seem to support it well enough. You can't set the env values on a per-server block basis. In other words, this won't work:

server {
    listen 80;
    server_name domain;
    env FOO = "bar";
}

You must do this:

env FOO = "bar";

http {
    server {
        listen 80;
        server_name domain;
    }
}

Which means that I can't have vhost-specific values. So I must create a whole vhost config for each site and only activate the one I want at the moment so that the value is set correctly.

Is there any way to work around this?

Best Answer

It turns out that if you are using fastcgi you can get around this by passing the values from fastcgi_param.

server {
    listen 80;
    server_name domain;

    # Pass PHP scripts to php-fastcgi listening on port 9000
    location ~ path/to/it {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param FOO "bar";
    }
}
Related Topic