nginx的ngx_http_geoip2模組以精準禁止特定地區IP訪問

  • 2019 年 10 月 6 日
  • 筆記

 

要求:對網站的資訊,比如某個訪問節點不想中國或者國外的用戶使用,禁止中國或者國外或者精確到某個城市的那種情況。

解決方式:1.Cloudfalre來實現禁止特定國家的ip訪問,比較簡單,但是需要money!!!

                  2.nginx,直接使用geoip模組,現在我們使用最新的ngx_http_geoip2,該模組可以精確到國家、省、市等一級的IP,並且全部由Nginx執行識別和阻止訪問,但是Nginx編譯起來比較費事。

最終解決方式,使用nginx的geoip模組:

部署操作:

一:安裝geoip2擴展依賴

yum install libmaxminddb-devel -y  

二:下載ngx_http_geoip2_module

git clone https://github.com/leev/ngx_http_geoip2_module.git  

注意要是沒有git的話就自己在網上下了然後直接拖到伺服器上也行,不過注意格式。

三:查看模組的完整性,將下載好的模組放到指定目錄下,方便nginx編譯時指定路徑,我是放到/usr/local/下面的。

 

 四:編譯nginx並檢查模組是否安裝成功

nginx建議選擇最新版本,我選的是1.18,也有說1.15都行的,選了1.18.之前選了1.15的沒成功。但是為了匹配最新版本,一下就成功了,只能感嘆神奇,所以選擇1.18是正確的,哈哈!

注意:在編譯時,我們只要加上–add-module=/usr/local/ngx_http_geoip2_module這個參數或者命令就行了,注意一定要加上額,不加等於沒有geoip模組,就更沒有這個功能了,為了簡化,具體的nginx編譯參數我就不寫了,如下。

  ./configure  --add-module=/usr/local/ngx_http_geoip2_module --user=www --group=www --prefix=......................................  

之後的功能make && make install 等照常規流程來就行了。  

nginx整體安裝完就檢查下模組是否都有:

[root@nsh install]# nginx -V  Tengine version: Tengine/2.3.2  nginx version: nginx/1.17.3  built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)  built with OpenSSL 1.1.1b  26 Feb 2019  TLS SNI support enabled  configure arguments: --add-module=/usr/local/ngx_http_geoip2_module --user=www --group=www --prefix=/www/server/nginx   --add-module=/www/server/nginx/src/ngx_devel_kit --add-module=/www/server/nginx/src/lua_nginx_module  --add-module=/www/server/nginx/src/ngx_cache_purge --add-module=/www/server/nginx/src/nginx-sticky-module   --with-openssl=/www/server/nginx/src/openssl --with-pcre=pcre-8.43 --with-http_v2_module --with-stream  --with-stream_ssl_module --with-http_stub_status_module --with-http_ssl_module --with-http_image_filter_module  --with-http_gzip_static_module --with-http_gunzip_module --with-ipv6 --with-http_sub_module --with-http_flv_module   --with-http_addition_module --with-http_realip_module --with-http_mp4_module  --with-ld-opt=-Wl,-E --with-cc-opt=-Wno-error --with-ld-opt=-ljemalloc  

五:驗證是否成功

ldd  /usr/local/nginx/sbin/nginx