问题
HAProxy provides a built-in http_err_rate
counter which “reports the average HTTP request error rate over that period.” This can be used in a stick table to rate-limit clients that are generating a lot of errors. That might look something like this:
frontend web
tcp-request content reject if { src_get_gpc0(Abuse) gt 0 }
acl scanner src_http_err_rate(Abuse) ge 10
http-request deny if scanner flag_abuser
backend Abuse
stick-table type ip size 1m expire 60m store gpc0,http_err_rate(20s)
What I'd like to do is track something like the http_err_rate
, but only for 401 Unauthorized
status codes. That way HAProxy would only be concerned with rate-limiting unauthorized requests, rather than all HTTP error codes.
Thanks!
回答1:
What I'd like to do is track something like the http_err_rate, but only for 401 Unauthorized status codes.
You can use the General Purpose Counters together with an ACL matching on the status fetch. The following example configuration will track the rate of 404 errors for a given IP address [1] and deny requests with the 429 status if a rate of 10 requests per 10 seconds is exceeded:
frontend fe_http
mode http
bind *:8080
stick-table type ipv6 size 10k expire 300s store gpc0_rate(10s)
http-request track-sc0 src
http-request deny deny_status 429 if { sc0_gpc0_rate gt 10 }
# Relevant line below
http-response sc-inc-gpc0(0) if { status 404 }
default_backend be_http
backend be_http
mode http
server example example.com:80
[1] Note: I recommend to use ipv6
as the stick table key, it may contain both IPv4 and IPv6 addresses.
回答2:
If you want to rate limit depending on their rate of 401 you need to change the 429 code by 401 in your config:
http-request deny deny_status 401 if { sc_http_req_cnt(0) gt 10 }
With both deny and tarpit you can add the deny_status flag to set a custom response code instead of the default 403/500 that they use out of the box. For example using http-request deny deny_status 429 will cause HAProxy to respond to the client with the error 429: Too Many Requests.
For more "general" information about acls and rate-limiting, you can see:
https://www.haproxy.com/blog/four-examples-of-haproxy-rate-limiting/ https://www.haproxy.com/blog/introduction-to-haproxy-acls/
来源:https://stackoverflow.com/questions/56015422/how-to-rate-limit-by-http-status-code-with-haproxy