本文實現的功能是:網站啟用訪問白名單,對于不在白名單中又需要訪問的客戶,只需打開一個不公開的網址,然后自動獲得2小時的訪問權限,時間達到后自動刪除訪問權限
實現此功能需要以下幾個步驟:
- nginx啟用訪問白名單
- 客戶打開指定網址自動添加訪問白名單
- 為網址添加簡單的認證
- 每兩個小時自動恢復默認白名單,刪除臨時IP訪問權限
一、nginx配置訪問白名單
這個就比較簡單了,簡單貼一下配置:
............nginx.conf...........
1
2
3
4
|
geo $remote_addr $ip_whitelist { default 0; include ip_white.conf; } |
............server段............
1
2
3
4
5
6
|
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代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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腳本內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/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
- 恢復默認的ip_white.conf文件,配合定時任務可以取消非默認IP的訪問權限
nginx主進程使用root運行,shell腳本reload nginx需設置粘滯位:
1
2
|
chown root.root /usr/local/nginx/sbin/nginx chmod 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中加入:
1
2
3
4
5
|
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
|
1 * /2 * * * root /opt/ngx_add .sh rec |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.52os.net/articles/nignx-add-ip-whitelist-on-demand.html