search
HomeOperation and MaintenanceNginxHow Nginx limits http resource requests
How Nginx limits http resource requestsMay 17, 2023 pm 12:16 PM
httpnginx

Prerequisite: nginx needs to have the ngx_http_limit_conn_module and ngx_http_limit_req_module modules. You can use the command 2>&1 nginx -v | tr ' ' '\n'|grep limit to check whether there are corresponding modules. If not, please recompile and install these two module.

The test version is: nginx version is 1.15

Limit the number of links

1. Use The limit_conn_zone directive defines the key and sets parameters for the shared memory zone (worker processes will use this zone to share a counter of key values). The first parameter specifies the expression to be evaluated as the key. The second parameter zone specifies the name and size of the zone:

limit_conn_zone $binary_remote_addr zone=addr:10m;

2. Use the limit_conn directive in the context of location {}, server {} or http {} to apply the limit. The first parameter is the value set above. The specified shared memory area name. The second parameter is the number of links allowed for each key:

location /download/ {
 limit_conn addr 1;
}

When using the $binary_remote_addr variable as a parameter, it is based on the restriction of the ip address. You can also use the $server_name variable. Limit the number of connections to a given server:

http {
 limit_conn_zone $server_name zone=servers:10m;

 server {
 limit_conn servers 1000;
 }
}

Limit request rate

Rate limiting can be used to prevent ddos, cc attacks, or to prevent upstream servers from being attacked at the same time Flooded with too many requests. This method is based on the leaky bucket algorithm, where requests arrive at the bucket at various rates and leave the bucket at a fixed rate. Before using rate limiting, you need to configure the global parameters of the "leaky bucket":

  • key - a parameter used to distinguish one client from another, usually the variable

  • shared memory zone - The name and size of the zone that holds the state of these keys (i.e. the "leaky bucket")

  • rate - Number of requests per second ( The request rate limit specified in r/s) or requests per minute (r/m) ("leaky bucket draining"). Requests per minute specifies a rate of less than one request per second.

These parameters are set using the limit_req_zone directive. This directive is defined at the http {} level - this approach allows applying different zones and requesting overflow parameters to different contexts:

http {
 #...

 limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
}

With this configuration, a 10m bytes size with the name one will be created Shared memory area. This area holds the state of the client ip address set using the $binary_remote_addr variable. Note that $remote_addr also contains the client's IP address, while $binary_remote_addr holds a shorter binary representation of the IP address.

The optimal size of the shared memory area can be calculated using the following data: The value size of $binary_remote_addr ipv4 address is 4 bytes, and the storage state on 64-bit platforms takes up 128 bytes. Therefore, state information for approximately 16000 IP addresses takes up 1m bytes of this area.

If storage space is exhausted when nginx needs to add new entries, the oldest entries will be deleted. If the freed space is still not enough to accommodate the new record, nginx will return a 503 service unavailable status code, which can be redefined using the limit_req_status directive.

Once this zone is set, you can limit the request rate using the limit_req directive anywhere in the nginx configuration, especially server {}, location {} and http {} Context:

http {
 #...

 limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

 server {
 #...

 location /search/ {
  limit_req zone=one;
 }
 }
}

Using the above configuration, nginx will process no more than 1 request per second under the /search/ route, and the way to delay processing these requests is that the total rate is no greater than the set rate. nginx will delay processing such requests until "bucket" (shared bucket one) is full. For requests to the full bucket, nginx will respond with a 503 service unavailable error (when limit_req_status does not have a custom set status code).

Limit bandwidth

To limit the bandwidth per connection, use the following limit_rate directive:

location /download/ {
 limit_rate 50k;
}

With this setting, the client Will be able to download content at speeds of up to 50k/sec over a single connection. However, clients can open multiple connections to bypass this limit. Therefore, if the goal is to prevent download speeds greater than a specified value, the number of connections should be limited as well. For example, one connection per IP address (if using the shared memory region specified above):

location /download/ {
 limit_conn addr 1;
 limit_rate 50k;
}

To impose a limit only after the client has downloaded a certain amount of data, use the limit_rate_after directive. It might be reasonable to allow the client to quickly download a certain amount of data (e.g. file header - movie index) and limit the rate at which the rest of the data is downloaded (making the user watch the movie instead of downloading).

limit_rate_after 500k;
limit_rate 20k;

The following example shows a combined configuration for limiting the number of connections and bandwidth. The maximum number of connections allowed is set to 5 connections per client address, which works for most common cases as modern browsers typically have a maximum of 3 connections open at a time. At the same time, the location provided for download only allows one connection:

http {
 limit_conn_zone $binary_remote_address zone=addr:10m

 server {
 root /www/data;
 limit_conn addr 5;

 location / {
 }

 location /download/ {
  limit_conn addr 1;
  limit_rate_after 1m;
  limit_rate 50k;
 }
 }
}

The above is the detailed content of How Nginx limits http resource requests. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Springboot怎么使用内置tomcat禁止不安全HTTPSpringboot怎么使用内置tomcat禁止不安全HTTPMay 12, 2023 am 11:49 AM

Springboot内置tomcat禁止不安全HTTP方法1、在tomcat的web.xml中可以配置如下内容让tomcat禁止不安全的HTTP方法/*PUTDELETEHEADOPTIONSTRACEBASIC2、Springboot使用内置tomcat没有web.xml配置文件,可以通过以下配置进行,简单来说就是要注入到Spring容器中@ConfigurationpublicclassTomcatConfig{@BeanpublicEmbeddedServletContainerFacto

JAVA发送HTTP请求的方式有哪些JAVA发送HTTP请求的方式有哪些Apr 15, 2023 am 09:04 AM

1.HttpURLConnection使用JDK原生提供的net,无需其他jar包,代码如下:importcom.alibaba.fastjson.JSON;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.HttpURLConnection;

nginx中如何升级到支持HTTP2.0nginx中如何升级到支持HTTP2.0May 24, 2023 pm 10:58 PM

一、前言#ssl写在443端口后面。这样http和https的链接都可以用listen443sslhttp2default_server;server_namechat.chengxinsong.cn;#hsts的合理使用,max-age表明hsts在浏览器中的缓存时间,includesubdomainscam参数指定应该在所有子域上启用hsts,preload参数表示预加载,通过strict-transport-security:max-age=0将缓存设置为0可以撤销hstsadd_head

Nginx的HTTP2协议优化与安全设置Nginx的HTTP2协议优化与安全设置Jun 10, 2023 am 10:24 AM

随着互联网的不断发展和改善,Web服务器在速度和性能上的需求也越来越高。为了满足这样的需求,Nginx已经成功地掌握了HTTP2协议并将其融入其服务器的性能中。HTTP2协议要比早期的HTTP协议更加高效,但同时也存在着特定的安全问题。本文将为您详细介绍如何进行Nginx的HTTP2协议优化和安全设置。一、Nginx的HTTP2协议优化1.启用HTTP2在N

Nginx中HTTP的keepalive怎么配置Nginx中HTTP的keepalive怎么配置May 12, 2023 am 11:28 AM

httpkeepalive在http早期,每个http请求都要求打开一个tpcsocket连接,并且使用一次之后就断开这个tcp连接。使用keep-alive可以改善这种状态,即在一次tcp连接中可以持续发送多份数据而不会断开连接。通过使用keep-alive机制,可以减少tcp连接建立次数,也意味着可以减少time_wait状态连接,以此提高性能和提高httpd服务器的吞吐率(更少的tcp连接意味着更少的系统内核调用,socket的accept()和close()调用)。但是,keep-ali

Python的HTTP客户端模块urllib与urllib3怎么使用Python的HTTP客户端模块urllib与urllib3怎么使用May 20, 2023 pm 07:58 PM

一、urllib概述:urllib是Python中请求url连接的官方标准库,就是你安装了python,这个库就已经可以直接使用了,基本上涵盖了基础的网络请求功能。在Python2中主要为urllib和urllib2,在Python3中整合成了urllib。Python3.x中将urllib2合并到了urllib,之后此包分成了以下四个模块:urllib.request:它是最基本的http请求模块,用来模拟发送请求urllib.error:异常处理模块,如果出现错误可以捕获这些异常urllib

怎么利用Java实现调用http请求怎么利用Java实现调用http请求Jun 02, 2023 pm 04:57 PM

一、概述在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)。在Java项目中调用第三方接口的方式有:1、通过JDK网络类Java.net.HttpURLConnection;2、通过common封装好的HttpClient;3、通过Apache封装好的CloseableHttpClient;4、通过SpringBoot-RestTemplate;二、Java调用第三方

Nginx http运行状况健康检查如何配置Nginx http运行状况健康检查如何配置May 14, 2023 pm 06:10 PM

被动检查对于被动健康检查,nginx和nginxplus会在事件发生时对其进行监控,并尝试恢复失败的连接。如果仍然无法恢复正常,nginx开源版和nginxplus会将服务器标记为不可用,并暂时停止向其发送请求,直到它再次标记为活动状态。上游服务器标记为不可用的条件是为每个上游服务器定义的,其中包含块中server指令的参数upstream:fail_timeout-设置服务器标记为不可用时必须进行多次失败尝试的时间,以及服务器标记为不可用的时间(默认为10秒)。max_fails-设置在fai

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft