nginx动态添加访问白名单
  1. nginx启用访问白名单

  2. 客户打开指定网址自动添加访问白名单

  3. 为网址添加简单的认证

  4. 每两个小时自动恢复默认白名单,删除临时IP访问权限

一、nginx配置访问白名单

这个就比较简单了,简单贴一下配置:

............nginx.conf...........
geo $remote_addr $ip_whitelist {
default 0;
include ip_white.conf;
}
............server段............
location / {
if ($ip_whitelist = 1) {
break;
}
return 403;
}

二、使用LUA自动添加白名单

nginx需配合lua模块才能实现这个功能,新建一个loC++ation,客户访问这个location时,使用lua拿到客户IP并调用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("添加白名单完成,有效时间最长为2小时");
';
}

/opt/ngx_add.sh shell脚本内容:

#!/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

该脚本有两个功能:

  1. 自动加IP并reload nginx

  2. 恢复默认的ip_white.conf文件,配合定时任务可以取消非默认IP的访问权限

nginx主进程使用root运行,shell脚本reload nginx需设置粘滞位:

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

nginx需启用lua模块

三、添加简单的认证

使用base auth 添加简单的用户名密码认证,防止非授权访问,生成密码文件:

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

账号:wpon.cn
密码:123456

在刚刚的location中加入:

location /addip {    
auth_basic "nginx auto addIP  for 52os.net";    
auth_basic_user_file /usr/local/nginx/conf/pass;     
autoindex on;    
......Lua代码略......

四、自动恢复默认IP白名单

通过web获得访问权限的IP,设置访问有效期为两小时,我是通过每两小时恢复一次默认的IP白名单文件实现。把ip_white.conf文件复制一份作为默认的白名单模版:

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

使用定时任务每两小时通用上面的shell脚本来恢复,定时任务为:

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