在 nginx.conf 中使用环境变量或参数
Use Environment Variable or Parameter in nginx.conf
我尝试在nginx.conf中添加一个proxy_pass like
location /example/ {
proxy_pass http://example.com;
}
但是我不想在 conf 文件中进行硬编码 http://example.com,而是希望在环境变量中包含此值。
如何在 nginx.conf 中使用环境变量?或者有没有更好的 nginx 没有外部配置的方法?
如果你想在 nginx 配置中加入纯环境变量,你需要用 Lua 语言实现一些代码:
https://blog.doismellburning.co.uk/environment-variables-in-nginx-config/
如果您对这个 NGinx 的负载不是很高,我建议实施上述解决方案。
在我的具体情况下,为了减少 CPU 负载,我更喜欢使用带有变量的分隔文件和 rc.local
(或 dockerfile)中的脚本来在启动机器时更改这些文件。
conf.d/exemple.conf
include backends/exemple.host;
location ~ ^/exemple {
proxy_pass $exemple;
}
backends/exemple.host
set $exemple {BACKEND};
rc.local
sed -i "s@set $exemple.*@set $exemple $HOSTNAME\;@" /etc/nginx/backends/exemple.host
为了最后的解决方案有效,我需要更改 O.S 上的 NGinx 启动顺序。
您可以使用 lua.
例如:
set_by_lua $curr_domain_name 'return os.getenv("DOMAIN")';
add_header Content-Security-Policy 'script-src ${curr_domain_name}';
这对我有用。
我尝试在nginx.conf中添加一个proxy_pass like
location /example/ {
proxy_pass http://example.com;
}
但是我不想在 conf 文件中进行硬编码 http://example.com,而是希望在环境变量中包含此值。
如何在 nginx.conf 中使用环境变量?或者有没有更好的 nginx 没有外部配置的方法?
如果你想在 nginx 配置中加入纯环境变量,你需要用 Lua 语言实现一些代码:
https://blog.doismellburning.co.uk/environment-variables-in-nginx-config/
如果您对这个 NGinx 的负载不是很高,我建议实施上述解决方案。
在我的具体情况下,为了减少 CPU 负载,我更喜欢使用带有变量的分隔文件和 rc.local
(或 dockerfile)中的脚本来在启动机器时更改这些文件。
conf.d/exemple.conf
include backends/exemple.host;
location ~ ^/exemple {
proxy_pass $exemple;
}
backends/exemple.host
set $exemple {BACKEND};
rc.local
sed -i "s@set $exemple.*@set $exemple $HOSTNAME\;@" /etc/nginx/backends/exemple.host
为了最后的解决方案有效,我需要更改 O.S 上的 NGinx 启动顺序。
您可以使用 lua.
例如:
set_by_lua $curr_domain_name 'return os.getenv("DOMAIN")';
add_header Content-Security-Policy 'script-src ${curr_domain_name}';
这对我有用。