DEV Community

Cover image for Rate Limit specific URLs using Nginx
Rhuaridh
Rhuaridh

Posted on

Rate Limit specific URLs using Nginx

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.

I will show you a simple way to rate limit specific URLs by using Nginx.

Video Walkthrough

The written instructions are below, but here is a quick video walkthrough showing how to apply rate limiting in Nginx.

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;
}
Enter fullscreen mode Exit fullscreen mode

Then within your location block, add:

limit_req zone=mylimit;
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
agost8 profile image
M.H.S πŸ‡ΈπŸ‡³

Thanks it's very useful