开发者

How to reference OS Environment Variables in nginx.conf

开发者 https://www.devze.com 2023-04-05 19:02 出处:网络
In nginx.conf. After set a variable by set 开发者_运维问答$name value, i can reference it like $name,

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 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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号