DEV Community

Cover image for Rate Limit specific URLs using Nginx
Rhuaridh
Rhuaridh

Posted on

11 5

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

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

Thanks it's very useful

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay