在 openresty nginx.conf 中,我希望能够根据功能标志值有条件地添加位置,如下所示
env ENABLE_UPSTREAMS;
env UPSTREAM_HOST;
http {
upstream upstream1 {
server ${UPSTREAM_HOST1};
}
upstream upstream2 {
server ${UPSTREAM_HOST2};
}
map $ENABLE_UPSTREAMS $enable_upstreams {
"on" 1;
default 0;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
if ($enable_upstreams = 1) {
location /some-path {
proxy_pass http://upstream1;
}
location /some-path-2 {
proxy_pass http://upstream2;
}
}
}
}
但这不起作用。我收到错误
"location" directive is not allowed here in /usr/local/
。
我尝试包含为单独的 *.conf 文件,但仍然出现相同的错误。
比我尝试过的
location /some-path {
if ($enable_aws_upstreams = 1) {
proxy_set_header Host $UPSTREAM_HOST;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://upstream2;
}
}
但这会导致另一个错误
"proxy_set_header" directive is not allowed here in
,而在另一边,如果被功能标志禁用,我不想公开任何路径
这种情况下正确的方法是什么?
仅允许在
if
块内使用少量指令(大多数 ngx_http_rewrite_module
指令,因为 if
本身是该模块的一部分); location
和 proxy_*
都是不允许的,因此会出现错误。
假设(从标签来看)您使用 OpenResty,我们可以使用
ngx_http_lua_module
的力量。
这是一个粗略的例子:
env ENABLE_UPSTREAMS;
http {
upstream disabled {
server 127.0.0.1:8001;
}
upstream upstream1 {
# upstream1 mock address for demo purposes
server 127.0.0.1:9001;
}
upstream upstream2 {
# upstream2 mock address for demo purposes
server 127.0.0.1:9002;
}
server {
listen 8000;
location /path-1 {
# we have to predefine the variable
set $upstream '';
# set the actual value depending of the environment variable value
set_by_lua_block $upstream {
if os.getenv('ENABLE_UPSTREAMS') == 'on' then
return 'upstream1'
else
return 'disabled'
end
}
proxy_pass http://$upstream;
}
location /path-2 {
set $upstream '';
set_by_lua_block $upstream {
if os.getenv('ENABLE_UPSTREAMS') == 'on' then
return 'upstream2'
else
return 'disabled'
end
}
proxy_pass http://$upstream;
}
}
# dummy "disabled" upstream, just returns 404
server {
listen 127.0.0.1:8001;
return 404;
}
# upstream1 mock for demo purposes
server {
listen 127.0.0.1:9001;
return 200 'response from upstream1';
}
# upstream2 mock for demo purposes
server {
listen 127.0.0.1:9002;
return 200 'response from upstream2';
}
}
没有环境变量:
$ openresty -p . -c nginx_if.conf
$ curl http://localhost:8000/path-1/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>openresty</center>
</body>
</html>
$ curl http://localhost:8000/path-2/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>openresty</center>
</body>
</html>
使用环境变量:
$ env ENABLE_UPSTREAMS=on openresty -p . -c nginx_if.conf
$ curl http://localhost:8000/path-1/
response from upstream1
$ curl http://localhost:8000/path-2/
response from upstream2