Nginx提供了ngx_http_limit_req_module来限制用户每秒请求的数量
配置和ngx_http_limit_conn_module类似
配置示例
map $http_x_forwarded_for $clientRealIp { ## 没有通过代理,直接用 remote_addr "" $remote_addr; ## 用正则匹配,从 x_forwarded_for 中取得用户的原始IP ~^(?P<firstIP>[0-9\.]+),?.*$ $firstIP; } # 定义一个限制规则one,根据用户真实IP地址$clientRealIp匹配,10m的链接池大小,每秒1个请求 limit_req_zone $clientRealIp zone=one:10m rate=1r/s; server { listen 80 default_server; location =/test_ip{ # 限制具体的请求地址,设定请求包burst大小 limit_req zone=one burst=5; default_type text/plain; echo remote_add is $remote_addr; echo http_x_forwarded_for is $http_x_forwarded_for; echo clientRealIp is $clientRealIp; } }
配置完毕,重启Nginx,然后通过JMeter并发测试,会在Nginx的error.log中看到如下信息:
[error] 3859#0: *1998 limiting requests, excess: 5.635 by zone "one", client: 10.118.27.155, server: localhost, request: "GET /test_ip HTTP/1.1", host: "10.118.27.201" [error] 3859#0: *1999 limiting requests, excess: 5.635 by zone "one", client: 10.118.27.155, server: localhost, request: "GET /test_ip HTTP/1.1", host: "10.118.27.201"
更多配置请查看官网
Leave a Reply