You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在源服务器返回401时通过用户IP对Nginx进行限流?

How to Enforce Stricter Rate Limits on IPs Triggering 401 Responses in Nginx

Got it, let’s work through this. You already have a baseline rate limit for your API with:

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

But you want to crack down on IPs that are making repeated unauthorized calls (those that get a 401 from your origin server). The problem with your first attempt is that Nginx’s limit_req runs before it gets a response from the origin—so you can’t directly use the 401 status code to trigger the limit during the same request cycle. Instead, we need to track these problematic IPs and apply a stricter limit to their subsequent requests.

Here are two reliable approaches, depending on whether you want to stick to vanilla Nginx or use a slightly more robust module:


Approach 1: Vanilla Nginx (Using Cookies)

This method requires no extra modules and is quick to set up. We’ll set a cookie when an IP gets a 401, then check for that cookie to apply a stricter limit on future requests.

  1. Define a stricter limit zone for unauthorized IPs:

    limit_req_zone $binary_remote_addr zone=unauthorized_api:10m rate=1r/s; # Adjust rate as needed (e.g., 1r/m for 1 per minute)
    
  2. Update your API location block to track 401s and apply limits:

    location /api {
        # Apply regular API rate limit to all requests
        limit_req zone=api burst=10 nodelay;
    
        # If the client has a cookie indicating past 401s, apply stricter limit
        if ($cookie_unauthorized_flag) {
            limit_req zone=unauthorized_api burst=2 nodelay;
        }
    
        proxy_pass http://your_origin_server;
        proxy_intercept_errors on; # Critical: Lets Nginx handle the 401 response
        error_page 401 = @handle_401;
    }
    
    # Handle 401 responses by setting a tracking cookie
    location @handle_401 {
        # Set a cookie that expires in 5 minutes (adjust Max-Age to your desired penalty window)
        add_header Set-Cookie "unauthorized_flag=1; Path=/api; Max-Age=300; HttpOnly; Secure";
        return 401; # Send the original 401 status to the client
    }
    

Pros & Cons:

  • ✅ No extra modules needed
  • ✅ Easy to implement
  • ❌ Can be bypassed if the client clears their cookies

Approach 2: Robust Tracking with Shared Memory (Using Keyval Module)

For a more persistent solution that can’t be bypassed by clearing cookies, use Nginx’s ngx_http_keyval_module (included in Nginx Plus, or compilable as a third-party module for open-source Nginx). This stores the list of unauthorized IPs in shared memory across all worker processes.

  1. Load the module and define shared memory zones in your http block:
    http {
        # Shared memory zone to track unauthorized IPs
        keyval_zone zone=unauthorized_ips:10m;
        keyval $binary_remote_addr $is_unauthorized zone=unauthorized_ips;
    
        # Your existing regular API limit zone
        limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;
        # Stricter limit zone for unauthorized IPs
        limit_req_zone $binary_remote_addr zone=unauthorized_api:10m rate=1r/s;
    
        server {
            location /api {
                # Apply stricter limit if IP is marked as unauthorized
                if ($is_unauthorized = 1) {
                    limit_req zone=unauthorized_api burst=2 nodelay;
                }
                # Regular limit for all other requests
                limit_req zone=api burst=10 nodelay;
    
                proxy_pass http://your_origin_server;
                proxy_intercept_errors on;
                error_page 401 = @handle_401;
            }
    
            location @handle_401 {
                # Mark the IP as unauthorized
                set $is_unauthorized 1;
                keyval_set $binary_remote_addr 1 zone=unauthorized_ips;
                # Auto-unmark the IP after 5 minutes (300 seconds)
                keyval_set_timeout $binary_remote_addr 300 zone=unauthorized_ips;
                return 401;
            }
        }
    }
    

Pros & Cons:

  • ✅ Persistent tracking across worker processes
  • ✅ Can’t be bypassed by clearing cookies
  • ❌ Requires the ngx_http_keyval_module (compilation needed for open-source Nginx)

Key Notes:

  • Adjust the rate and burst values to match your desired strictness. For example, rate=1r/m would block all but 1 request per minute for unauthorized IPs.
  • The proxy_intercept_errors on directive is mandatory—it tells Nginx to intercept upstream error responses (like 401) so we can add our tracking logic instead of passing the response directly to the client.
  • If you want to apply the stricter limit immediately on the 401 request (not just future ones), you’ll need to use a Lua-based solution (like OpenResty), but that’s more complex. The above methods focus on punishing repeat offenders, which is usually the goal for unauthorized access attempts.

内容的提问来源于stack exchange,提问作者JuanDoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:22:27