简体   繁体   中英

Nginx TCP stream routing based on source IP

I have configured nginx as a reverse proxy for a TCP (non-http) stream. I'd like to apply different routing for a particular source IP address - can this be done, and how? I'm aware of recomendations for the http module using the if directive, but that doesn't seem to work for these streams.

Existing configuration:

stream {
  server {
    listen 8000;
    proxy_pass staging;
  }
}

upstream staging {
    server 1.2.3.4:8000;
}

Desired configuration (not working):

stream {
  server {
    listen 8000;
    proxy_pass staging1;
    if ( $remote_addr ~* 4.5.6.7 ) {
        proxy_pass staging2;
    }
  }
}

upstream staging1 {
    server 1.2.3.4:8000;
}
upstream staging2 {
    server 1.2.3.44:8000;
}

This gives error '24314#24314: "if" directive is not allowed here', since it doesn't apply for the stream module - is there any other functionality how I could achieve this result?

in case some people are still wondering you can achieve this using a map:

stream {
  upstream staging1 {
    server 1.2.3.4:8000;
  }

  upstream staging2 {
    server 1.2.3.44:8000;
  }

  map $remote_addr $backend_svr {
    4.5.6.7 "staging2";
    default "staging1";
  }
  server {
    listen 8000;
    proxy_pass $backend_svr;
  }
}

ref

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM