5. Nginx basic module-Nginx access restriction

1 Nginx access restrictions

This situation is often encountered, such as abnormal server traffic, excessive load, etc. For malicious access to traffic, it will cause waste of bandwidth, server pressure, and business impact. Often consider the number of connections to the same IP and concurrent The number is limited.

The ngx_http_limit_conn_module module can limit the number of connections for each key value according to a certain key, just like the number of connections from an IP source

limit_conn_module connection frequency limit

limit_req_module request frequency limit

HTTP connection and request

HTTP is built on TCP. To complete the HTTP request, you need to establish a TCP three-way handshake (called a TCP connection), and then the HTTP request is based on the connection.

An HTTP request is based on a TCP connection, and a TCP request generates at least one HTTP request.

variable:

The length of the $binary_remote_addr variable is fixed 4 bytes

The length of the $remote_addr variable is 7-15 bytes

IP ip address 32bit=4 bytes

1.1 Nginx connection restriction syntax

Syntax:limit_conn_zone key zone=name:size;

Default:–

Context:http

Syntax:limit_conn zone number;

Default:-

Context:http, server, location

1.2 How to use the code

Nginx connection limit practice

http {
//http段配置连接显示,同一时刻只允许一个客户端IP连接
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
......
		server	{
......
					location	/ {
.....
						limit_conn conn_zone 1;	 //同一时刻只允许一个客户端ip连接
		}
}

Nginx request limit combat

http	{
//http段配置请求限制,rate限制速率,限制一秒钟最多一个ip请求
limit_req_zone $binary_remote_addr zone=req_game:10m  rate=1r/s;	
.....
	server {	
	......
			location  / 	{
			//1r/s只接受一个请求,,其余请求决绝并返回错误代码给客户端
					#limit_req zone=req_game;		
			//请求超过1r/s,剩下的将被延迟处理,请求数超过burst定义的数量,多余的请求返回503
					limit_req zone=req_game burst=3 nodelay;
			}
	}
}

1.3 Stress test

Use ab tools for stress testing

yum install -y httpd-tools

[root@nginx_web1 ~]# ab -n 50 -c 20 http://127.0.0.1/index.html
Insert picture description here

4.4 Nginx connection limit is not valid as request limit

As we said before, multiple requests can establish a tcp connection again, so the accuracy of our request is of course more effective than restricting a link, because only one connection request is allowed to enter at the same time, but multiple at the same time The request can be entered through a connection. So we request that the restriction is a better solution.

Guess you like

Origin blog.csdn.net/weixin_43357497/article/details/113764058