nginx动态添加访问白名单的方法
本文实现的功能是:网站启用访问白名单,对于不在白名单中又需要访问的客户,只需打开一个不公开的网址,然后自动获得2小时的访问权限,时间达到后自动删除访问权限
实现此功能需要以下几个步骤:
- nginx启用访问白名单
- 客户打开指定网址自动添加访问白名单
- 为网址添加简单的认证
- 每两个小时自动恢复默认白名单,删除临时IP访问权限
一、nginx配置访问白名单
这个就比较简单了,简单贴一下配置:
............nginx.conf...........
geo$remote_addr$ip_whitelist{ default0; includeip_white.conf; }
............server段............
location/{ if($ip_whitelist=1){ break; } return403; }
启用白名单的IP写在ip_white.conf文件中,格式为:8.8.8.81;,只需将IP按照格式写入ip_white.conf中即可获得访问权限。
二、使用LUA自动添加白名单
nginx需配合lua模块才能实现这个功能,新建一个location,客户访问这个location时,使用lua拿到客户IP并调用shell脚本写入ip_white.conf中,写入后自动reloadnginx使配置生效,lua代码:
location/addip{ content_by_lua' CLIENT_IP=ngx.req.get_headers()["X_real_ip"] ifCLIENT_IP==nilthen CLIENT_IP=ngx.req.get_headers()["X_Forwarded_For"] end ifCLIENT_IP==nilthen CLIENT_IP=ngx.var.remote_addr end ifCLIENT_IP==nilthen 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.shshell脚本内容:
#!/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$1in rec) rm-rf$ngx_conf cp$ngx_back$ngx_conf /usr/local/nginx/sbin/nginx-sreload ;; *) if[-z"$result"] then echo"#####addbyweb#####">>$ngx_conf echo"$11;">>$ngx_conf /usr/local/nginx/sbin/nginx-sreload else exit0 fi ;; esac
该脚本有两个功能:
- 自动加IP并reloadnginx
- 恢复默认的ip_white.conf文件,配合定时任务可以取消非默认IP的访问权限
nginx主进程使用root运行,shell脚本reloadnginx需设置粘滞位:
chownroot.root/usr/local/nginx/sbin/nginx chmod4755/usr/local/nginx/sbin/nginx
nginx启用lua模块见nginx启用lua模块
三、添加简单的认证
使用baseauth添加简单的用户名密码认证,防止非授权访问,生成密码文件:
printf"52os.net:$(opensslpasswd-crypt123456)\n">>/usr/local/nginx/conf/pass
账号:52os.net
密码:123456
在刚刚的location中加入:
location/addip{ auth_basic"nginxautoaddIPfor52os.net"; auth_basic_user_file/usr/local/nginx/conf/pass; autoindexon;
......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.shrec
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。