本文實現的功能是:網站啟用訪問白名單,對于不在白名單中又需要訪問的客戶,只需打開一個不公開的網址,然后自動獲得2小時的訪問權限,時間達到后自動刪除訪問權限
實現此功能需要以下幾個步驟:
nginx啟用訪問白名單 客戶打開指定網址自動添加訪問白名單 為網址添加簡單的認證 每兩個小時自動恢復默認白名單,刪除臨時IP訪問權限一、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
該腳本有兩個功能:
自動加IP并reload nginx 恢復默認的ip_white.conf文件,配合定時任務可以取消非默認IP的訪問權限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 添加簡單的用戶名密碼認證,防止非授權訪問,生成密碼文件:
復制代碼 代碼如下:
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;
新聞熱點
疑難解答