欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

nginx動態(tài)添加訪問白名單的方法

 更新時(shí)間:2017年02月09日 09:13:41   作者:閱心筆記  
本篇文章主要介紹了nginx動態(tài)添加訪問白名單的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本文實(shí)現(xiàn)的功能是:網(wǎng)站啟用訪問白名單,對于不在白名單中又需要訪問的客戶,只需打開一個不公開的網(wǎng)址,然后自動獲得2小時(shí)的訪問權(quán)限,時(shí)間達(dá)到后自動刪除訪問權(quán)限

實(shí)現(xiàn)此功能需要以下幾個步驟:

  • nginx啟用訪問白名單
  • 客戶打開指定網(wǎng)址自動添加訪問白名單
  • 為網(wǎng)址添加簡單的認(rèn)證
  • 每兩個小時(shí)自動恢復(fù)默認(rèn)白名單,刪除臨時(shí)IP訪問權(quán)限

一、nginx配置訪問白名單

這個就比較簡單了,簡單貼一下配置:

............nginx.conf...........

geo $remote_addr $ip_whitelist {
default 0;
include ip_white.conf;
}

............server段............

location / {
  if ($ip_whitelist = 1) {
   break;
  }
  return 403;
 }

啟用白名單的IP寫在ip_white.conf文件中,格式為: 8.8.8.8 1;,只需將IP按照格式寫入ip_white.conf中即可獲得訪問權(quán)限。

二、使用LUA自動添加白名單

nginx需配合lua模塊才能實(shí)現(xiàn)這個功能,新建一個location,客戶訪問這個location時(shí),使用lua拿到客戶IP并調(diào)用shell腳本寫入ip_white.conf中,寫入后自動reload nginx使配置生效,lua代碼:

location /addip {
content_by_lua '

CLIENT_IP = ngx.req.get_headers()["X_real_ip"]
if CLIENT_IP == nil then
 CLIENT_IP = ngx.req.get_headers()["X_Forwarded_For"]
end
if CLIENT_IP == nil then
 CLIENT_IP = ngx.var.remote_addr
end
if CLIENT_IP == nil then
 CLIENT_IP = "unknown"
end
 ngx.header.content_type = "text/html;charset=UTF-8";
 ngx.say("你的IP : "..CLIENT_IP.."<br/>");
 os.execute("/opt/ngx_add.sh "..CLIENT_IP.."")
 ngx.say("添加白名單完成,有效時(shí)間最長為2小時(shí)");
';
}

/opt/ngx_add.sh shell腳本內(nèi)容:

#!/bin/bash
ngx_conf=/usr/local/nginx/conf/52os.net/ip_white.conf
ngx_back=/usr/local/nginx/conf/52os.net/ip_white.conf.default
result=`cat $ngx_conf |grep $1`

case $1 in

rec)
 rm -rf $ngx_conf 
 cp $ngx_back $ngx_conf
  /usr/local/nginx/sbin/nginx -s reload
 ;;

*)
 if [ -z "$result" ]
  then
   echo "#####add by web #####" >>$ngx_conf
   echo "$1 1;" >> $ngx_conf
   /usr/local/nginx/sbin/nginx -s reload
  else
   exit 0
  fi
;;
esac

該腳本有兩個功能:

  • 自動加IP并reload nginx
  • 恢復(fù)默認(rèn)的ip_white.conf文件,配合定時(shí)任務(wù)可以取消非默認(rèn)IP的訪問權(quán)限

nginx主進(jìn)程使用root運(yùn)行,shell腳本reload nginx需設(shè)置粘滯位:

chown root.root /usr/local/nginx/sbin/nginx
chmod 4755 /usr/local/nginx/sbin/nginx

nginx啟用lua模塊見nginx啟用lua模塊

三、添加簡單的認(rèn)證

使用base auth 添加簡單的用戶名密碼認(rèn)證,防止非授權(quán)訪問,生成密碼文件:

復(fù)制代碼 代碼如下:

printf "52os.net:$(openssl passwd -crypt 123456)\n" >>/usr/local/nginx/conf/pass

賬號:52os.net

密碼:123456

在剛剛的location中加入:

location /addip {

   auth_basic "nginx auto addIP for 52os.net";
   auth_basic_user_file /usr/local/nginx/conf/pass; 
   autoindex on;

......Lua代碼略......

四、自動恢復(fù)默認(rèn)IP白名單

通過web獲得訪問權(quán)限的IP,設(shè)置訪問有效期為兩小時(shí),我是通過每兩小時(shí)恢復(fù)一次默認(rèn)的IP白名單文件實(shí)現(xiàn)。把ip_white.conf文件復(fù)制一份作為默認(rèn)的白名單模版:

復(fù)制代碼 代碼如下:

cp /usr/local/nginx/conf/52os.net/ip_white.conf /usr/local/nginx/conf/52os.net/ip_white.conf.default

使用定時(shí)任務(wù)每兩小時(shí)通用上面的shell腳本來恢復(fù),定時(shí)任務(wù)為:

1 */2 * * * root /opt/ngx_add.sh rec

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論