本文先容如何利用GeoIP模塊讓nginx實現限制某個地域用戶會見的成果。nginx要加上 --with-http_geoip_module 參數舉辦編譯。
1、首先我們查抄一下nginx是否編譯了GeoIP模塊
nginx -V
假如你在輸出界面看到了 --with-http_geoip_module,那么就說明nginx已經編譯了GeoIP模塊。
2、接下來我們安裝GeoIP數據庫
在Debian/Ubuntu系統,我們可以執行下面的呼吁舉辦安裝:
apt-get install geoip-database libgeoip1
安裝完成之后,GeoIP數據庫會被安裝在 /usr/share/GeoIP/GeoIP.dat。
這個GeoIP.dat是GeoIP數據庫文件,利用apt-get呼吁安裝的話這個文件不是最新的,我們可以從 http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz 這里下載最新的GeoIP數據庫文件。
mv /usr/share/GeoIP/GeoIP.dat /usr/share/GeoIP/GeoIP.dat_bak
cd /usr/share/GeoIP/
wget
http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
3、此刻來設置nginx.conf文件
vi /etc/nginx/nginx.conf
將下面的內容添加進 http {} 區域,而且要放在任何 include 語句之前。
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default yes;
FK no;
FM no;
EH no;
}
上面這些語句是除了 FK,新加坡云主機 香港云主機,FM,EH這三個地域的用戶答允其它地域的用戶會見。
也可以只答允部門地域用戶會見:
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
FK yes;
FM yes;
EH yes;
}
上面這些語句是除了 FK,FM,EH這三個地域的用戶其它地域的用戶都不答允會見。
上面的語句只是配置了一個 $allowed_country 變量,要最終實現克制配置的地域用戶會見,我們要對 $allowed_country 變量舉辦判定處理懲罰。
在 server {} 區域里添加以下內容:
if ($allowed_country = no) {
return 403;
}
也可以針對某個特定url舉辦限制:
location /special {
if ($allowd_country = no) {
return 403;
}
}
4、重啟nginx
/etc/init.d/nginx reload
這樣我們就實現了nginx限制某個地域用戶會見的成果。