In an openresty nginx.conf I would like be able to add locations conditionally based on a feature flag value, like as it follows
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;
}
}
}
}
but this does not work. I get as error "location" directive is not allowed here in /usr/local/.
I tried to include as a separate *.conf file but still the same error.
than I tried
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;
}
}
but this end in another error "proxy_set_header" directive is not allowed here in and on other side I do not want to expose any path if is disabled by feature flag
What is the right way in this case?
Only handful of directives are allowed inside
ifblock (mostyngx_http_rewrite_moduledirectives sinceifitself is a part of this module); neitherlocationnorproxy_*is allowed, hence the error.Assuming (from the tag) that you use OpenResty, we can use the power of
ngx_http_lua_module.Here is a rough example:
Without the env variable:
With the env variable: