最近有一個網站項目需求:需要屏蔽國內的方問請求?;〞r間研究了一下這方面的資料。目前找到的最佳方法就是使用 Nginx 的 GeoIP 模塊來實現地區的識別。然后配置相關國家的 ISO 名稱,禁止訪問即可。記錄一下相關過程。
編譯 GeoIP 組件
maxmind 提供的免費版數據庫已經可以滿足需求,在使用數據庫前,需要先編譯 GeoIP 組件:
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.8.tar.gz./configuremakemake install
下載 IP 庫
從 maxmind 下載 IP 數據包并解壓。 這個是國家的ip數據包:
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gzgunzip GeoIP.dat.gz
這個是城市的ip數據包:
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gzgunzip GeoLiteCity.dat.gz
執行完上面的命令后,會得到 GeoIP.dat 和 GeoLiteCity.dat 文件。將這兩個文件復制到 Nginx 的 conf 目錄。
編譯 Nginx
nginx默認不編譯這個模塊,需要開啟--with-http_geoip_module編譯選項。
模塊依賴MaxMind GeoIP庫。
配置 Nginx
接下來就需要配置 Nginx,首先需要在 Nginx 配置文件中的 http 區塊中加載 GeoIP 的數據包:
geoip_country GeoIP.dat;geoip_city GeoLiteCity.dat;
禁止國家訪問
只需要在網站的 Nginx 配置中加入下面的示例的代碼:
if ($geoip_country_code = CN) { deny all;}
上面的配置表示只要是國內的 IP,就拒絕訪問。
GeoIP 組件配置項參考
GeoIP 中跟國家相關的變量:
$geoip_country_code #兩位字符的英文國家碼。如:CN, US$geoip_country_code3 #三位字符的英文國家碼。如:CHN, USA$geoip_country_name #國家英文全稱。如:China, United States
GeoIP 中跟國家下級區域相關的變量:
$geoip_city_country_code #也是兩位字符的英文國家碼。$geoip_city_country_code3 #上同$geoip_city_country_name #上同.$geoip_region #這個經測試是兩位數的數字,如杭州是02, 上海是 23。但是沒有搜到相關資料,希望知道的朋友留言告之。$geoip_city #城市的英文名稱。如:Hangzhou$geoip_postal_code #城市的郵政編碼。經測試,國內這字段為空$geoip_city_continent_code #不知什么用途,國內好像都是AS$geoip_latitude #緯度$geoip_longitude #經度
在 php 中測試 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;
新聞熱點
疑難解答