我能够使用limit_req
来限制所有请求到我的服务器。
但是,我想删除某些IP地址(即白名单)的速率限制,并对某些IP地址使用不同的速率限制(即某些IP,我想低至1r / s)。
我尝试使用条件(例如, if ( $remote_addr = "1.2.3.4" ) {}
),但似乎只适用于重写规则,而不是速率限制规则。
避免使用“if”指令更好。 当limit_req_zone(和limit_conn_zone)中的键为空时,不会应用限制。 您可以将其与地图和地理模块结合使用,以创build不应用油门限制的IP白名单。
此示例显示如何为来自单个IP的并发请求和请求速率configuration限制。
http { geo $whitelist { default 0; # CIDR in the list below are not limited 1.2.3.0/24 1; 9.10.11.12/32 1; 127.0.0.1/32 1; } map $whitelist $limit { 0 $binary_remote_addr; 1 ""; } # The directives below limit concurrent connections from a # non-whitelisted IP address to five limit_conn_zone $limit zone=connlimit:10m; limit_conn connlimit 5; limit_conn_log_level warn; # logging level when threshold exceeded limit_conn_status 503; # the error code to return # The code below limits the number requests from a non-whitelisted IP # to one every two seconds with up to 3 requests per IP delayed # until the average time between responses reaches the threshold. # Further requests over and above this limit will result # in an immediate 503 error. limit_req_zone $limit zone=one:10m rate=30r/m; limit_req zone=one burst=3; limit_req_log_level warn; limit_req_status 503;
区域指令必须放置在http级别,但其他指令可以放在更远的位置,例如在服务器或位置级别,以限制其范围或进一步调整限制。
有关更多信息,请参阅Nginx文档ngx_http_limit_req_module和ngx_http_limit_conn_module
您可以安全地使用命名的位置,例如if()块中的“@location”。
请参阅: http : //wiki.nginx.org/IfIsEvil
像这样的东西应该工作:
http { limit_req_zone $binary_remote_addr zone=delay:10m rate=1r/m; server { ... error_page 410 = @slowdown; if( $remote_addr != "1.2.3.4" ) { return 410; } location @slowdown { limit_req zone=delay burst 5; ... } location / { ... } }
使用与“location / {}”相同的信息填写“location @slowdown {}”,如果您使用nginx作为反向代理,则使用proxy_pass。