如何在nginx中使用系统的环境变量(转)

Environment Variables

Using environment variables to store sensitive or system-dependant information is a well-known and popular practice.

Thus it is a bit surprising that Nginx doesn't come with any built-in facility to access them from its config files. Some people go around this by including a step in their deployment process which "generates" the final configuration files replacing the variable names with the appropiate values.

In fact, the first google searches seem to indicate that this is the only possibility. Fortunately, there are others.

With Lua

If you are using Openresty, or have the ngx_lua module and ngx_devel_kit module installed, you are in luck.

You first need to declare what variables you'll be needing somewhere in your nginx.conf file using the envdirective:

env API_KEY;

After that, when you want to access the environment variable, you can use a combination of set_by_lua and os.getenv, like this:

http {   ...   server {     location / {       set_by_lua $api_key 'return os.getenv("API_KEY")';       ...     }   } }

In this example we are assigning the environment variable to one of Nginx variables; we can use $api_key as a regular nginx.conf variable.

With Perl

Using Lua was our preferred approach, since we have OpenResty. If you can't use Lua, a second solution involves using Perl. The first part is similar; you must declare the variables he uses using env:

env API_KEY;

After that, you can combine perl_set and some Perl to do the same thing as before:

http {   ...   server {     location / {       perl_set $api_key 'sub { return $ENV{"API_KEY"}; }';       ...     }   } }

You will need to have the ngx_http_perl_module module enabled in order to be able to use this technique.

Conclusion

It is a bit surprising that Nginx doesn't provide this seemingly basic feature out of the box, but fortunately this is easily solvable with modules.

Finding out exactly how to do so, however, was more difficult than expected; the information was segregated into several mailing lists (we're including references to them at the end).

Hopefully this blogpost will make this stuff a bit easier to find.

P.S. If you're curious to see what APItools can do, you can sign up here, it's free.

References

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值