【问题标题】:How to block a page for certain countries (geoip2) without if?如何在没有 if 的情况下阻止某些国家/地区(geoip2)的页面?
【发布时间】:2021-01-12 05:20:08
【问题描述】:

如何不使用 if 而是使用 ma​​p 在 nginx 中使用模块 --with_geoip2_module (动态)来阻止除所选国家之外的所有国家和除选择,让它像这样工作:

**if ($lan = yes) {
              set $allowed_country yes;
      }

if ($allowed_country = no) {
       return 503;
  }**

但没有如果

Centos 7

这是我的 /etc/nginx/nginx.conf

load_module modules/ngx_http_geoip2_module.so;

user nginx;

worker_processes  1;

error_log  /var/log/nginx/error.log warn;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

#block country

 geoip2 /etc/nginx/geoip/GeoLite2-Country/GeoLite2-Country.mmdb {

auto_reload 60m;
$geoip2_data_country_code country iso_code;
$geoip2_data_country_name country names en;
}  

geo $lan {
 default no;
 123.224.55.2 yes;

  }


map $geoip2_data_country_code $allowed_country {
    
    default no;
    UA yes;
    BG yes;
    RO yes;
}

   log_format geoip_main '$remote_addr - $geoip2_data_country_code - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent "$host" '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log  /var/log/nginx/access.log geoip_main;

access_log /var/log/nginx/geoip_country.log geoip_main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;

access_log /var/log/nginx/geoip_country.log geoip_main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
 include include/etc/nginx/modules/*.so;

}

非常感谢您的帮助!

【问题讨论】:

  • 我认为这根本不可能。无论如何,你不应该担心if (...) { return 503; } 块,它是完全安全的。您可以使用附加的 map 指令代替您的第一个 if 块。
  • 感谢您的回答,我该如何为第二条指令写这个?

标签: nginx ip centos7 geoip geoip2


【解决方案1】:

一篇NGINX官方文章says

如果在位置上下文中,可以在内部完成的唯一 100% 安全的事情是:

return ...;
rewrite ... last;

所以你的if (...) { return 503; } 块是完全安全的。要排除第一个 if 块,请使用

geo $lan {
    default no;
    123.224.55.2 yes;
}
map $geoip2_data_country_code $allowed_country {
    default no;
    UA yes;
    BG yes;
    RO yes;
}
map $lan$allowed_country $deny {
    ~yes "";
    default 1;
}
...
server {
    ...
    if ($deny) {
        return 503;
    }
    ...
}

更新

此版本具有相同的功能,并且应该稍快一些,因为它不使用正则表达式匹配:

geo $lan {
    default  0;
    123.224.55.2  1;
    ...
}
map $geoip2_data_country_code $allowed_country {
    default  0;
    UA  1;
    BG  1;
    RO  1;
}
map $lan$allowed_country $deny {
    default  0;
    00  1;
}
...
server {
    ...
    if ($deny) {
        return 503;
    }
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多