Home > Operation and Maintenance > Nginx > How to limit access frequency per unit time in nginx

How to limit access frequency per unit time in nginx

WBOY
Release: 2023-05-15 13:43:06
forward
842 people have browsed it

First of all, I will say that I encountered this problem because the website was attacked and Alibaba Cloud called the police. I thought of limiting the access frequency instead of limiting IP addresses (the plan for limiting IP addresses will be given later). The status code returned by nginx when the connection resources are exhausted is 502. After adding the restrictions of this solution, it returns 599, which is different from the normal status code.
The steps are as follows:

First add the following content to nginx.conf:

map $http_x_forwarded_for  $clientrealip {
    "" $remote_addr;
    ~^(?p<firstaddr>[0-9\.]+),?.*$  $firstaddr;
    }

    ###safe setting to limit the request number per second
    limit_req_status 599;
    limit_req_zone $clientrealip zone=allips:70m rate=5r/s;
Copy after login

The session pool size is 70m. If there are many restricted IPs, you can adjust it smaller. If there are few restricted IPs, If there are many accessible IPs, you need to increase
to 5 requests per second. This is also adjusted according to the situation. 5 is more appropriate or a little too large.

Then modify www.xxoo.com.conf (this is lnmp’s configuration file for each virtual host). In the server, add the following line above the location:

limit_req zone=allips burst=5 nodelay;
Copy after login

Restart nginx in this way You can write a script to test concurrency.

A python concurrent script is provided as follows:

import threading
import time,urllib2


url = &#39;http://sf.gg/&#39;
def worker():
  try:
   response = urllib2.urlopen(url)
   print response.getcode()
  except urllib2.httperror, e:
   print e.code

for i in range(2000):
  t = threading.thread(target=worker)
  t.start()
Copy after login

Both 2000 and http://sf.gg/ can be modified, and then execute python *.py > out to analyze out The status codes in the file are distributed. If 599 is particularly common, the frequency limit will play a role.

The above is the detailed content of How to limit access frequency per unit time in nginx. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template