nginx TCP forwarding with GeoIP

CentOS 7.8

nginx version: nginx/1.18.0

yum install nginx-module-geoip

yum install GeoIP GeoIP-data

Then, GeoIO runs well with HTTP(S).

I need nginx to forward a TCP port, which is only open to CN add to nginx.conf

stream {
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    log_format proxy '$remote_addr [$time_local] '
                 '$protocol $status $bytes_sent $bytes_received '
                 '$session_time "$upstream_addr" '
                 '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

    access_log /var/log/nginx/tcp-access.log proxy ;
    open_log_file_cache off;
    include tcpconf.d/*.conf;
}

xxxx.com.conf

server {
    listen   11111;
 
    proxy_pass  127.0.0.1:31688;
}

Forwarding 11111 to 31688 works OK.

add to server{

restart error enter image description here


Solution 1:

Your problem is with "if", which you should avoid as much as possible. Have a look at eg. nginx config example for another way.

There, a map is used to test the country code. A very simple version would be:

map $geoip_country_code $allow_visit {
    default no;
    CN yes;
    BE yes;
}
 
server{
  if ($allow_visit = no) {
    return 403;
  }
}

But this can't be used by stream, since "if" is part of the http_rewrite module. See eg. if in stream. I tried the following construct with success:

http {
  server {
    listen 9998;
    return 403;
  }
}

stream {
  geoip_country         /usr/share/GeoIP/GeoIP.dat;
  map $geoip_country_code $be_server {
    BE   127.0.0.1:9997;
    default 127.0.0.1:9998;

  }
  server {
    listen 9999;
    proxy_pass  $be_server;
  }
  server {
    listen 9997;
    proxy_pass 127.0.0.1:8889;
  }
}

Only requests from Belgium are allowed.