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;


server {
    listen   11111;

Forwarding 11111 to 31688 works OK.

add to server{

restart error enter image description here


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;
  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 {

  server {
    listen 9999;
    proxy_pass  $be_server;
  server {
    listen 9997;

Only requests from Belgium are allowed.

  • I edit the question,please see it – qq77273364 Dec 22 '20 at 7:44
  • I think I found a way out. – Gerard H. Pille Dec 22 '20 at 14:30
  • real situation 9998 is tcp port ,no http .I create a 9998.conf listen 9998 and 8889,copy stream{} to nginx.conf.no change BE,restart nginx.can access from CN and JP – qq77273364 Dec 25 '20 at 11:42
  • I don't understand. Please add your current configuration in a readable way to your question. – Gerard H. Pille Dec 25 '20 at 11:53
  • Like SSH, how to allow only CN connections. I thought of using nginx for forwarding – qq77273364 Dec 28 '20 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.