NGINX – Set Proxy Header Using Variable

configurationnginxnginx-reverse-proxyreverse-proxy

According to the NGINX documentation

proxy_set_header field value allows redefining or appending fields to the request header passed to the proxied server. The value can contain text, variables, and their combinations.

So I can do

set $my_variable "some_value";
proxy_set_header x-my-header $my_variable;

Is it anyhow possible to use a variable for the field parameter, i.e. have the header name based on a variable? I want to be able to configure NGINX like

set $my_variable "x-my-header";
proxy_set_header $my_variable "some_value";

Best Answer

When nginx documentation does not explicitly says that you can use variables for some directive parameter, generally it means you cannot. In particular you can't use variables as the header names in add_header, proxy_set_header and some other related directives. However you can do it using third party modules, e.g. lua-nginx-module via ngx.req.set_header. You can take a look at the OpenResty bundle which includes aforementioned module and is being packaged for a wide range of OS distributions.