Score:0

Use header variable in NGINX to forward traffic

in flag

I am using NGINX (nginx Docker image) as a reverse proxy and want to use the $host variable in stream/server context to forward the traffic to specific host which is defined in the Host header parameter of the incoming request. The configuration is the following:

events {
}

stream {
  log_format log_stream '$remote_addr [$time_local] $protocol'
  '$status $bytes_sent $bytes_received $session_time';

  access_log /var/log/nginx/access.log log_stream;
  error_log  /var/log/nginx/error.log;

  server {
    resolver 8.8.8.8 ipv6=off;
    listen       127.0.0.1:18443;
    proxy_pass   $host:443;
  }
}

There is an error during starting:

[emerg] 1#1: unknown "host" variable

According to the nginx documentation this variable should be populated. Do you know how can i use it inside the server directive to forward the traffic? Can i use other header parameter with specified hostname/address to forward the traffic?

Michael Hampton avatar
cz flag
What host name? There is no such variable in the stream context. You are just proxying a raw TCP stream. What host header?
ttsokov avatar
in flag
What about this [$hostname](https://nginx.org/en/docs/stream/ngx_stream_core_module.html#var_hostname) variable from the ngx_stream_core_module
Michael Hampton avatar
cz flag
That is the hostname of the system on which nginx is running (or in the case of Docker, the random container name).
Score:1
us flag

Your intention seems to be to pass through TLS connection via nginx stream module. If you want to target different destinations depending on the SNI field of TLS header, then you need to use the following configuration:

map $ssl_preread_server_name $destination {
    host1.example.com backend1;
    host2.example.com backend2;
    default backend3;
}

stream {
    upstream backend1 {
        server 192.168.100.1:443;
    }

    upstream backend2 {
        server 192.168.100.2:443;
    }

    upstream backend3 {
        server 192.168.100.3:443;
    }

    server {
        listen 127.0.0.1:443;
        proxy_pass $destination;
    }
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.