最近有一個(gè)網(wǎng)站項(xiàng)目需求:需要屏蔽國(guó)內(nèi)的方問(wèn)請(qǐng)求。花時(shí)間研究了一下這方面的資料。目前找到的最佳方法就是使用 Nginx 的 GeoIP 模塊來(lái)實(shí)現(xiàn)地區(qū)的識(shí)別。然后配置相關(guān)國(guó)家的 ISO 名稱,禁止訪問(wèn)即可。記錄一下相關(guān)過(guò)程。
編譯 GeoIP 組件
maxmind 提供的免費(fèi)版數(shù)據(jù)庫(kù)已經(jīng)可以滿足需求,在使用數(shù)據(jù)庫(kù)前,需要先編譯 GeoIP 組件:
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.8.tar.gz./configuremakemake install
下載 IP 庫(kù)
從 maxmind 下載 IP 數(shù)據(jù)包并解壓。 這個(gè)是國(guó)家的ip數(shù)據(jù)包:
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gzgunzip GeoIP.dat.gz
這個(gè)是城市的ip數(shù)據(jù)包:
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gzgunzip GeoLiteCity.dat.gz
執(zhí)行完上面的命令后,會(huì)得到 GeoIP.dat 和 GeoLiteCity.dat 文件。將這兩個(gè)文件復(fù)制到 Nginx 的 conf 目錄。
編譯 Nginx
nginx默認(rèn)不編譯這個(gè)模塊,需要開(kāi)啟--with-http_geoip_module編譯選項(xiàng)。
模塊依賴MaxMind GeoIP庫(kù)。
配置 Nginx
接下來(lái)就需要配置 Nginx,首先需要在 Nginx 配置文件中的 http 區(qū)塊中加載 GeoIP 的數(shù)據(jù)包:
geoip_country GeoIP.dat;geoip_city GeoLiteCity.dat;
禁止國(guó)家訪問(wèn)
只需要在網(wǎng)站的 Nginx 配置中加入下面的示例的代碼:
if ($geoip_country_code = CN) { deny all;}上面的配置表示只要是國(guó)內(nèi)的 IP,就拒絕訪問(wèn)。
GeoIP 組件配置項(xiàng)參考
GeoIP 中跟國(guó)家相關(guān)的變量:
$geoip_country_code #兩位字符的英文國(guó)家碼。如:CN, US$geoip_country_code3 #三位字符的英文國(guó)家碼。如:CHN, USA$geoip_country_name #國(guó)家英文全稱。如:China, United States
GeoIP 中跟國(guó)家下級(jí)區(qū)域相關(guān)的變量:
$geoip_city_country_code #也是兩位字符的英文國(guó)家碼。$geoip_city_country_code3 #上同$geoip_city_country_name #上同.$geoip_region #這個(gè)經(jīng)測(cè)試是兩位數(shù)的數(shù)字,如杭州是02, 上海是 23。但是沒(méi)有搜到相關(guān)資料,希望知道的朋友留言告之。$geoip_city #城市的英文名稱。如:Hangzhou$geoip_postal_code #城市的郵政編碼。經(jīng)測(cè)試,國(guó)內(nèi)這字段為空$geoip_city_continent_code #不知什么用途,國(guó)內(nèi)好像都是AS$geoip_latitude #緯度$geoip_longitude #經(jīng)度
在 php 中測(cè)試 GeoIP
首先需要在 fastcgi_params 或 fastcgi.conf 中引入 GeoIP 的屬性:
fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;fastcgi_param GEOIP_REGION $geoip_region;fastcgi_param GEOIP_CITY $geoip_city;fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;fastcgi_param GEOIP_LATITUDE $geoip_latitude;fastcgi_param GEOIP_LONGITUDE $geoip_longitude;
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注