nginx限制IP訪問網站:php
1.設置白名單:linux
#在虛擬主機配置文件中allow指定容許訪問的地址爲127.0.0.1,容許訪問的網段爲192.168.234.0/24,dney all 拒絕除容許的IP和IP段之外的全部地址訪問nginx
測試:安全
白名單IP:127.0.0.1服務器
[root@linux ~]# curl -I -x127.0.0.1:80 http://www.blog.com/ HTTP/1.1 200 OK
#http狀態碼200,能夠訪問curl
白名單網段192.168.234.0/24中的IP:ide
[root@linux ~]# curl -I -x192.168.234.128:80 http://www.blog.com/ HTTP/1.1 200 OK
#http狀態碼200,能夠訪問測試
白名單以外的IP:網站
[root@linux ~]# curl -I -x192.168.1.100:80 http://www.blog.com/ HTTP/1.1 403 Forbidden
#http狀態碼403,拒絕訪問ui
補充:-x指定的IP地址得是本地存在且在使用的IP
2.設置黑名單:
#deny將127.0.0.1設置爲黑名單,除127.0.0.1以外的IP都能訪問
測試:
黑名單IP 127.0.0.1:
[root@linux ~]# curl -I -x127.0.01:80 http://www.blog.com/ HTTP/1.1 403 Forbidden
#http狀態碼403,拒絕訪問
黑名單之外的IP 192.168.234.128:
[root@linux ~]# curl -I -x192.168.234.128:80 http://www.blog.com/ HTTP/1.1 200 OK
#http狀態碼200,能夠訪問
nginx限制IP訪問指定目錄:
測試網站www.blog.com下有個目錄爲admin/,限制IP訪問該目錄,編輯nginx虛擬主機配置文件,添加如下內容:
#容許192.168.234.0/24網段的IP訪問/admin目錄,拒絕127.0.0.1訪問/admin
測試:
容許訪問的IP:
[root@linux ~]# curl -I -x192.168.234.128:80 www.blog.com/admin/a.txt HTTP/1.1 200 OK
#http狀態碼200,能夠訪問
禁止訪問/admin目錄的IP 127.0.0.1:
[root@linux ~]# curl -I -x127.0.0.1:80 www.blog.com/admin/a.txt HTTP/1.1 403 Forbidden
#http狀態碼403,拒絕訪問
nginx限制IP訪問指定目錄下的某類文件:
測試網站www.blog.com下有個目錄爲admin/,該目錄中有不少.php的文件,爲了安全,須要限制全部IP訪問該目錄下的.php文件,編輯nginx虛擬主機配置文件,添加以下內容:
location ~ .*(upload|admin)/.*\.php$ { deny all; }
#該配置表示禁止全部IP訪問upload/和admin/目錄下的全部.php文件
測試:
[root@linux ~]# curl -I -x127.0.0.1:80 www.blog.com/admin/login.php HTTP/1.1 403 Forbidden
#http狀態碼403,拒絕訪問
nginx經過user-agent訪問標識限制爬蟲:
當網站訪問日誌中user-agent出現大量異常的訪問標識時(好比:Spider/3.0、YoudaoBot、Tomato等),能夠經過限制user-agent包含的關鍵字符拒絕爬蟲,節省服務器帶寬等
編輯nginx虛擬主機配置文件添加如下內容:
if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato') { return 403; }
#該配置表示當匹配到user-agent訪問表示中包含Spider/3.0、YoudaoBot、Tomato等關鍵詞的時候,拒絕訪問
測試:
[root@linux ~]# curl -I -A 'testSpider/3.0' -x127.0.0.1:80 www.blog.com HTTP/1.1 403 Forbidden
#http狀態碼403,拒絕訪問(curl -A參數:指定user-agent標識)
nginx經過$request_uri匹配關鍵字限制訪問:
什麼是$request_uri ?
request_uri :請求的連接,包括$document_uri和$args
測試用url:http://test.bbs.com/home.php?mod=space&uid=1&do=profile
uri:home.php?mod=space&uid=1&do=profile
document_uri:home.php
args:mod=space&uid=1&do=profile
經過匹配uri 中的關鍵詞進行訪問限制,編輯nginx虛擬主機配置文件添加如下內容:
if ($request_uri ~ (abc|999)) { return 403; }
#當uri 中包含關鍵詞abc或999時,將拒絕訪問
測試:
訪問測試用url:
[root@linux ~]# curl -I -x127.0.0.1:80 http://test.bbs.com/home.php?mod=space&uid=1&do=profile HTTP/1.1 200 OK
#http狀態碼200,能夠訪問
將uri中document_uri 更改成abc.php:
[root@linux ~]# curl -I -x127.0.0.1:80 http://test.bbs.com/abc.php?mod=space&uid=1&do=profile HTTP/1.1 403 Forbidden
#htpp狀態碼403,拒絕訪問
將uri中args 加入999關鍵詞:
[root@linux ~]# curl -I -x127.0.0.1:80 http://test.bbs.com/home.php?mod=space999&uid=1&do=profile HTTP/1.1 403 Forbidden
#http狀態碼403,拒絕訪問
補充:
當在nginx虛擬主機配置文件中添加的內容爲 if 判斷時,不能夠限制指定IP,只能return返回http狀態碼,限制指定的IP只能在全局或者location中直接allow或deny