Skip to content

Instantly share code, notes, and snippets.

@eagleon
Created September 4, 2023 08:10
Show Gist options
  • Save eagleon/45bd3320388d081c4e4d02ba1b773c56 to your computer and use it in GitHub Desktop.
Save eagleon/45bd3320388d081c4e4d02ba1b773c56 to your computer and use it in GitHub Desktop.
Nginx封禁国外IP

1.编译相关模块并,安装Nginx

# 安装libmaxminddb https://github.com/maxmind/libmaxminddb
git clone https://github.com/maxmind/libmaxminddb
./configure
make
make check
sudo make install
sudo ldconfig

# Nginx
wget http://nginx.org/download/nginx-VERSION.tar.gz
tar zxvf nginx-VERSION.tar.gz
cd nginx-VERSION

# 安装ngx_http_geoip2_module https://github.com/leev/ngx_http_geoip2_module
# 下载ngx_http_geoip2_module
./configure --add-module=/path/to/ngx_http_geoip2_module
make
make install

2.下载maxmind数据库

3.配置Nginx

http {
    ...
    geoip2 /opt/geo/maxmind-country.mmdb {
        auto_reload 5m;
        $geoip2_metadata_country_build metadata build_epoch;
        $geoip2_data_country_code default=US country iso_code;
        $geoip2_data_country_name country names en;
    }
    log_format main    '$remote_addr - [$time_local] "$request" [:$server_port] $status $bytes_sent "$http_referer" "$http_user_agent" "$request_time" "$upstream_response_time" "$upstream_addr" [$http_true_client_ip] [$http_x_forwarded_for][$http_x_api_request_id][$upstream_http_ccb_request_id][$geoip2_data_country_code]';

    server {
      server_name tdlz-cd-test.ccb.today;
      access_log /usr/local/nginx/logs/tdlz.access.log main;

      listen 80;
      if ($geoip2_data_country_code != "CN") {
        return 403;
      }

      location /tdlz {
        ...
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }
      
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment