How to reference OS Environment Variables in nginx

2020-08-25 05:36发布

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.

标签: nginx
2条回答
ゆ 、 Hurt°
2楼-- · 2020-08-25 05:49

It should be $name_from_env, just like any other Nginx variable.

Note that env can only be used in the main part of your config, not http, server or location blocks.

I'm guessing that env isn't really what you need in any case. If you are trying to pass variables down to your application, you should use proxy_param or fastcgi_param (depending on how you are talking to your upstream):

fastcgi_param MYVAR foo;
查看更多
做自己的国王
3楼-- · 2020-08-25 06:10

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.

查看更多
登录 后发表回答