NginxにGeoIP2モジュールを導入する手順

  1. 既存のNginx設定をバックアップ

  2. Nginxバージョンを切り替え(ソースコードディレクトリ /www/server/nginx/src を生成するため)

  3. GeoIP2モジュールの依存関係をインストール

libmaxminddbをダウンロード

Releases · maxmind/libmaxminddb (github.com)

tar zxvf libmaxminddb-1.10.0.tar.gz
cd libmaxminddb-1.10.0
./configure --prefix=/usr/local/libmaxminddb
make && make install
echo /usr/local/libmaxminddb/lib >> /etc/ld.so.conf
ldconfig
cd ..

必要なパッケージをインストール

yum install -y git gcc-c++ pcre-devel zlib-devel openssl-devel
git clone https://github.com/leev/ngx_http_geoip2_module.git /opt/geoip2_module
  1. NginxをコンパイルしGeoIP2モジュールを追加
cd /www/server/nginx/src
nginx -V > current_configure.txt
ORIGINAL_CONFIGURE=$(cat current_configure.txt | grep -oP "(?<=configure arguments: ).*")
./configure $ORIGINAL_CONFIGURE --add-module=/opt/geoip2_module
make && make install
systemctl restart nginx
  1. GeoIP2データベースを設定
mkdir -p /var/lib/geoip
cd /var/lib/geoip

GeoLite2無料データベースをダウンロード:

GeoLite2 Free Geolocation Data | MaxMind Developer Portal

アップロードしたファイルを解凍し、.mmdbファイルを配置

nginx.confのhttpセクションに追加:

    log_format geoip_format '$remote_addr - $remote_user [$time_local] "$request" '
                           '$status $body_bytes_sent "$http_referer" '
                           '"$http_user_agent" "$country_code" "$city_name"';
    
    set_real_ip_from   10.0.0.0/8;
    set_real_ip_from   172.16.0.0/12;
    set_real_ip_from   192.168.0.0/16;
    real_ip_header     X-Forwarded-For;
    real_ip_recursive  on;
    
    geoip2 /var/lib/geoip/GeoLite2-Country.mmdb {
        $country_code country iso_code;
        $country_name country names ja;
        $continent_code continent code;
    }
    
    geoip2 /var/lib/geoip/GeoLite2-City.mmdb {
        auto_reload 60m;
        $city_name city names ja;
        $region_name subdivisions 0 names ja;
        $region_iso subdivisions 0 iso_code;
        $latitude location latitude;
        $longitude location longitude;
    }

サイト設定ファイルに追加:

    location / {
        add_header X-Country-Code $country_code;
        add_header X-City-Name $city_name;
        add_header X-Region-Name $region_name;
    }
    
    access_log /var/log/nginx/geoip_access.log geoip_format;

サイトにアクセスし、ログファイルとレスポンスヘッダーを確認

  1. GeoIP2データベースの自動更新を設定

geoipupdateをダウンロード

Releases · maxmind/geoipupdate (github.com)

tar xzf geoipupdate_7.0.1_linux_amd64.tar.gz
mv geoipupdate_7.0.1_linux_amd64 /usr/local/bin/geoipupdate
chmod +x /usr/local/bin/geoipupdate

MaxMindサイトにログインし、ライセンスキーを生成

/etc/GeoIP.confを作成:

AccountID YOUR_ACCOUNT_ID
LicenseKey YOUR_LICENSE_KEY
EditionIDs GeoLite2-Country GeoLite2-City
DatabaseDirectory /var/lib/geoip
LockFile /var/lib/geoip/.geoipupdate.lock

cronタスクを設定:

crontab -e

0 2 * * * /usr/local/bin/geoipupdate -f /etc/GeoIP.conf -d /var/lib/geoip

タグ: nginx geoip2 baota 地理位置 lua

5月30日 07:51 投稿