Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference OS Environment Variables in nginx.conf

Tags:

nginx

In nginx.conf.

After set a variable by set $name value, i can reference it like $name,

But when I export an OS Environment Variable by env name_from_env, like https://nginx.org/en/docs/ngx_core_module.html#env said, and i am sure the name_from_env is valid which defined form nginx's parent process.

But, my friends, how to reference it ? $name_from_env or ${name_from_env} or %name_from_env% didn't work what I've tried before.

like image 732
caoxingk Avatar asked Sep 16 '11 02:09

caoxingk


1 Answers

nginx doesn't have the built-in ability to reference its environment variables in the configuration at present. The simplest solution however is the perl_set directive from ngx_http_perl_module, an extra module for nginx. The official nginx packaging builds the Perl module dynamically so it's a case of ensuring you install the extra nginx-module-perl package (or configure your custom build of nginx, if that's what you're doing).

Configuration looks like this:

# Make environment variable available
env NAME_FROM_ENV;
# Load dynamic module (if built with Perl as dynamic module; omit if static)
load_module modules/ngx_http_perl_module.so;

http {
    server {
        location / {
            # Use Lua to get get and set the variable
            perl_set $name_from_env 'sub { return $ENV{"NAME_FROM_ENV"}; }';
            ...
        }
    }
}

See also https://docs.apitools.com/blog/2014/07/02/using-environment-variables-in-nginx-conf.html for how to use Lua to achieve the same thing. Lua support requires a third party module and isn't shipped with nginx's default packages.

like image 97
davidjb Avatar answered Oct 19 '22 15:10

davidjb