API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · 课时

使用 Nginx 进行速率限制与流量控制

设置速率限制,保护后端服务免受滥用,并确保资源得到公平使用。

第 3 / 4 课11 个步骤

使用 Nginx 进行速率限制与流量控制 是 CoddyKit 上的免费 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Rate Limiting Matters

Imagine a popular website or API. What happens if one user or a malicious bot sends thousands of requests per second?

This is where rate limiting comes in! It's a crucial technique to control the number of requests a client can make to your server within a specific timeframe.

  • Prevents abuse and DDoS attacks.
  • Ensures fair resource usage for all clients.
  • Protects your backend services from overload.

Nginx's Key Directives

Nginx provides powerful directives to implement rate limiting. We'll focus on two main ones:

  • limit_req_zone: Defines the parameters for a rate limiting zone. Think of it as setting up the rules for a specific type of traffic.
  • limit_req: Applies the defined rate limiting rules to requests within a specific location or server block. This is where the magic happens!

Defining Your Rate Limit Zone

The limit_req_zone directive is typically placed in the http block of your Nginx configuration. It defines a shared memory zone where Nginx keeps track of request states.

Here's its structure and what each part means:

  • key: What Nginx tracks (e.g., $binary_remote_addr for client IP).
  • zone: A name for your zone and its size (e.g., my_limit:10m). The size determines how many unique keys Nginx can track.
  • rate: The actual rate limit (e.g., rate=1r/s for 1 request per second).

Setting Up Your First Zone

Let's define a simple rate limiting zone that tracks requests by client IP address and allows 5 requests per second.

http {
    # ... other http settings ...

    limit_req_zone $binary_remote_addr zone=my_ip_limit:10m rate=5r/s;

    server {
        # ...
    }
}

Attaching Limits to Locations

After defining a limit_req_zone, you need to apply it to specific parts of your website or API using the limit_req directive.

This directive is placed inside a server or location block. It simply references the zone you created earlier.

For example, to apply the my_ip_limit zone to a specific location:

limit_req zone=my_ip_limit;

When a client exceeds the defined rate, Nginx will return a 503 Service Unavailable error by default.

A Complete Basic Rate Limit

Here's how you can combine both directives to limit requests to your /api/ endpoint to 2 requests per second per unique IP address.

http {
    limit_req_zone $binary_remote_addr zone=api_requests:10m rate=2r/s;

    server {
        listen 80;
        server_name example.com;

        location /api/ {
            limit_req zone=api_requests;
            proxy_pass http://backend_service;
        }
    }
}

Allowing Temporary Spikes

Strict rate limits can sometimes be too restrictive for legitimate users. The burst parameter allows a client to make requests exceeding the defined rate temporarily.

  • burst=N: Allows requests up to N more than the rate limit. These requests are queued and processed at the rate limit.
  • nodelay: When used with burst, Nginx processes burst requests immediately if possible. If the queue is full, subsequent requests are dropped (503 error) instead of being delayed.

Without nodelay, requests exceeding the rate will be delayed to conform to the rate.

Rate Limiting with Burst Tolerance

Let's update our previous example to allow a burst of up to 5 additional requests, processing them immediately if resources permit.

http {
    limit_req_zone $binary_remote_addr zone=api_requests:10m rate=2r/s;

    server {
        listen 80;
        server_name example.com;

        location /api/ {
            limit_req zone=api_requests burst=5 nodelay;
            proxy_pass http://backend_service;
        }
    }
}

Rate Limiting vs. Throttling

While often used interchangeably, there's a subtle difference:

  • Rate Limiting: Enforces a hard limit on the number of requests over a period (e.g., 100 requests per minute). Nginx's limit_req primarily implements rate limiting.
  • Throttling: Is a more dynamic process that might slow down requests rather than outright rejecting them. It often considers server load or resource availability. While Nginx can delay requests with burst (if nodelay is absent), it's more focused on strict limits.

For most API protection needs, Nginx's rate limiting capabilities are robust and highly effective.

Quick Check

You've learned about the core Nginx directives for rate limiting. Now, let's test your knowledge!

Summary: Protecting Your APIs

In this lesson, you've learned how to implement rate limiting with Nginx to protect your backend services and ensure fair usage.

  • We defined a rate limiting zone using limit_req_zone.
  • We applied these limits to specific locations using limit_req.
  • We explored the burst and nodelay options to handle temporary traffic spikes more gracefully.

Rate limiting is a fundamental security and performance pattern, especially when dealing with public APIs or high-traffic web applications.

免费开始

用 AI 导师学习 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「使用 Nginx 进行速率限制与流量控制」课时是免费的吗?

是的 — 「使用 Nginx 进行速率限制与流量控制」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课程的其余内容,请升级到 CoddyKit PRO。 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课程共包含 4 节课。

「使用 Nginx 进行速率限制与流量控制」这节课中我会学到什么?

设置速率限制,保护后端服务免受滥用,并确保资源得到公平使用。 你通过在浏览器中直接运行的动手代码来练习 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 Nginx 进行速率限制与流量控制」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课中编写并运行代码吗?

能。每节 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Nginx 实现 API 版本管理
  2. 跨源资源共享(CORS)
  3. 使用 Nginx 进行速率限制与流量控制
  4. 基于路径的微服务路由
← 返回 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)