本文實現的功能是:網站啟用訪問白名單,對于不在白名單中又需要訪問的客戶,只需打開一個不公開的網址,然后自動獲得2小時的訪問權限,時間達到后自動刪除訪問權限
實現此功能需要以下幾個步驟:
一、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中即可獲得訪問權限。
二、使用LUA自動添加白名單
nginx需配合lua模塊才能實現這個功能,新建一個location,客戶訪問這個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"]endif CLIENT_IP == nil then CLIENT_IP = ngx.var.remote_addrendif 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/bashngx_conf=/usr/local/nginx/conf/52os.net/ip_white.confngx_back=/usr/local/nginx/conf/52os.net/ip_white.conf.defaultresult=`cat $ngx_conf |grep $1`case $1 inrec) 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
該腳本有兩個功能:
nginx主進程使用root運行,shell腳本reload nginx需設置粘滯位:
chown root.root /usr/local/nginx/sbin/nginxchmod 4755 /usr/local/nginx/sbin/nginx
nginx啟用lua模塊見nginx啟用lua模塊
三、添加簡單的認證
使用base auth 添加簡單的用戶名密碼認證,防止非授權訪問,生成密碼文件:
賬號: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代碼略......
四、自動恢復默認IP白名單
通過web獲得訪問權限的IP,設置訪問有效期為兩小時,我是通過每兩小時恢復一次默認的IP白名單文件實現。把ip_white.conf文件復制一份作為默認的白名單模版:
使用定時任務每兩小時通用上面的shell腳本來恢復,定時任務為:
1 */2 * * * root /opt/ngx_add.sh rec
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答