Building DevSecOps solutions using AWS, Terraform and Kubernetes

Nginx Tips - Rate Limit Url Map

  • 18th September 2021
"Terrible at creating videos, great at buiding e-commerce solutions"

Why rate limit?

Rate limiting is a simple way of stopping users (hopefully just the bad ones!) from accessing more of your sites resources than you would like.

It's often much easier to implement rate limiting at the firewall layer. However, let's explore adding rate limiting at the the nginx layer

How to add rate limiting in nginx

At the top of you nginx file, you can define a map like so:

limit_req_zone $binary_remote_addr_map zone=mylimit:10m rate=5r/s;
limit_req_status 429;

map $request_uri $binary_remote_addr_map {
    default "";
    ~^/what-is-new.html $binary_remote_addr;
    ~^/another-url-to-rate-limit.html $binary_remote_addr;
}

Be sure to replace the zone and rate values with amounts relevant to your application.

Then within your location block, add:

limit_req zone=mylimit;

And that's it! Now only webpages matching the $request_uri will have rate limiting applied. This is handy when you have all of your request being routed through a single place, but you only want to have specific pages on your site rate limited.

Further information

If you would like to learn more please check out the nginx blog post on this:

Rhuaridh

Please get in touch through my socials if you would like to ask any questions - I am always happy to speak tech!