nginx 屏蔽惡意請求


https://www.xlongwei.com/detail/nginx-%E5%B1%8F%E8%94%BD%E6%81%B6%E6%84%8F%E8%AF%B7%E6%B1%82

nginx可以很方便地做訪問控制,特別是一些偶發性的大量惡意請求,需要屏蔽處理。

  • 屏蔽ip地址
location /someapi/ {
allow ip; #特定接口只開放給某個ip調用
deny all;
}

location /somepage/ {
deny ip; #屏蔽某個ip訪問(iptables可以拒絕某個ip連接)
allow all;
}

 

  • 屏蔽user-agent
if ($http_user_agent = Mozilla/5.0 ) { return 403; }   #有些請求頭很明顯不是用戶瀏覽器


分析nginx日志,找出惡意ip或user-agent

cat /var/log/nginx/access.log | awk -F\" '{A[$(NF-1)]++}END{for(k in A)print A[k],k}' | sort -n |tail
122 58.144.7.66
337 106.91.201.75
2270 122.200.77.170 #顯然這個ip不正常,而且這不是nginx所知道的真實ip,而是$http_x_forwarded_for變量

 

  • 屏蔽代理ip,有兩種情形會需要屏蔽代理ip:一是代理ip訪問,二是負載均衡(real-ip請求負載均衡服務器,再代理給后端server)
vi /etc/nginx/badproxy.rules
map $http_x_forwarded_for $badproxy {
default 0;
~*122.200.77.170 1; #建立映射
}
vi /etc/nginx/nginx.conf
http {
include /etc/nginx/badproxy.rules #這個要在server配置之前
server {
location /somepage/ {
if ( $badproxy ) { return 403; }
}
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM