basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ManualHomelabnginx

    Rate limiting and access control in nginx: limit_req, Cloudflare, auth_request, mTLS, and CrowdSec

    Set up brute-force protection (limit_req and limit_conn) with an IP allowlist, restore the real client IP behind Cloudflare via realip, lock down admin panels four ways (allow/deny, auth_basic, auth_request, mTLS client certificates), and add log-based bans with CrowdSec.

    Real client IP behind Cloudflare or another proxy (realip)

    When Cloudflare or another load balancer sits in front of nginx, $remote_addr (and $binary_remote_addr inside rate limits) contains the proxy IP unless ngx_http_realip_module is configured. Without it, allow/deny, limit_req, and CrowdSec act on CDN edge nodes and cut off all traffic.

    # /etc/nginx/conf.d/02-realip.conf — inside the http context
    # Pull the current subnet list from https://www.cloudflare.com/ips-v4 and /ips-v6
    set_real_ip_from 173.245.48.0/20;
    set_real_ip_from 103.21.244.0/22;
    set_real_ip_from 103.22.200.0/22;
    # … remaining Cloudflare IPv4 and IPv6 ranges
    
    real_ip_header CF-Connecting-IP;
    real_ip_recursive on;

    If your own reverse proxy sits on the local network (10.0.0.10), use set_real_ip_from 10.0.0.10; and real_ip_header X-Forwarded-For;.

    Rate limiting (limit_req) and connection limits (limit_conn)

    limit_req uses a leaky bucket: requests pass through at the configured rate, while short spikes (a browser fetching 15 assets on page load) are absorbed by the burst queue.

    • Without nodelay, requests in burst wait in the queue and are released with an artificial delay.
    • With nodelay, bursts up to burst are served immediately, and anything over the cap gets 429 Too Many Requests right away (nginx defaults to 503 — switch to standard 429 via limit_req_status 429;).

    To exempt your monitoring probes and office IP, build the zone key with geo and map: an empty string key skips the limit for that address.

    /etc/nginx/conf.d/03-ratelimit.conf
    geo $limit_bypass {
        default 0;
        127.0.0.1/32    1;
        203.0.113.50/32 1;
    }
    
    map $limit_bypass $limit_key {
        0 $binary_remote_addr;
        1 "";
    }

    IP allowlist: matching addresses get an empty $limit_key, bypassing limit_req. Everyone else is keyed by $binary_remote_addr (4 bytes for IPv4 instead of a 15-byte string).

    limit_req_zone  $limit_key zone=site_req:10m  rate=10r/s;
    limit_req_zone  $limit_key zone=login_req:10m rate=5r/m;
    limit_conn_zone $limit_key zone=per_ip_conn:10m;
    
    limit_req_status  429;
    limit_conn_status 429;
    Key part

    Two separate shared-memory zones: a relaxed one for regular pages (10r/s, 10 MB holds roughly 160,000 addresses) and a strict one for login (5r/m — at most one request every 12 seconds). Plus per_ip_conn to cap concurrent connections.

    server {
        listen 443 ssl;
        server_name app.example.org;
    
        location / {
            limit_req zone=site_req burst=20 nodelay;
            limit_conn per_ip_conn 20;
            proxy_pass http://127.0.0.1:3000;
        }
    
        location = /login {
            limit_req zone=login_req burst=3 nodelay;
            proxy_pass http://127.0.0.1:3000;
        }
    }

    Applied inside server: the whole site allows a 20-request burst and up to 20 concurrent connections; /login permits only 3 rapid attempts before returning 429.

    Locking down admin panels: four options by security level

    If… Use
    access is needed only from one or two static IPs or a VPN subnet allow / deny
    you want a quick password on an internal page without setting up SSO auth_basic over HTTPS
    multiple services should share one login with 2FA (Authelia, Authentik, Tinyauth) auth_request
    you want cryptographic access with no passwords or login forms (personal server, private API) mTLS (ssl_verify_client on)

    1. IP filtering (allow / deny)

    Rules are evaluated top to bottom until the first match:

    location /admin/ {
        allow 10.0.0.0/24;
        allow 203.0.113.50;
        deny all;
        proxy_pass http://127.0.0.1:3000;
    }

    2. HTTP password (auth_basic)

    Create a bcrypt password file (-B, from apache2-utils) and grant read permission to the nginx group:

    sudo apt install -y apache2-utils
    sudo htpasswd -cB /etc/nginx/.htpasswd example-user
    sudo chown root:nginx /etc/nginx/.htpasswd
    sudo chmod 640 /etc/nginx/.htpasswd
    location /admin/ {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
        proxy_pass http://127.0.0.1:3000;
    }

    auth_basic sends credentials Base64-encoded in the Authorization header, so use it only over HTTPS. To allow access by IP or password (trusted LAN without a password, external clients with a password), add satisfy any;.

    3. External authorization (auth_request)

    The nginx equivalent of Traefik’s forwardAuth: before every request to /admin/, nginx sends an internal subrequest to a local auth service (Authelia, Tinyauth, or a custom microservice). On 200, nginx forwards the request and can pass the username via auth_request_set; on 401 or 403, it rejects the client (or redirects to a login page via error_page 401 = @login).

    location = /_auth {
        internal;
        proxy_pass http://127.0.0.1:9091/api/authz/auth-request;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
        proxy_set_header X-Original-Method $request_method;
    }
    
    location /admin/ {
        auth_request /_auth;
        auth_request_set $auth_user $upstream_http_remote_user;
        proxy_set_header Remote-User $auth_user;
        proxy_pass http://127.0.0.1:3000;
    }

    4. Client certificate (mTLS)

    nginx verifies the client’s own certificate during the TLS handshake: without a key signed by your trusted local CA, the client receives 400 Bad Request before any HTTP request reaches the app.

    server {
        listen 443 ssl;
        http2 on;
        server_name admin.example.org;
    
        ssl_certificate        /etc/letsencrypt/live/admin.example.org/fullchain.pem;
        ssl_certificate_key    /etc/letsencrypt/live/admin.example.org/privkey.pem;
        ssl_client_certificate /etc/nginx/certs/client-ca.crt;
        ssl_verify_client      on;
    
        location / {
            proxy_set_header X-Client-CN $ssl_client_s_dn;
            proxy_pass http://127.0.0.1:3000;
        }
    }

    Integrating with CrowdSec

    Unlike limit_req, which tracks only request rate per IP, CrowdSec parses nginx access.log and error.log against attack scenarios (.env/.git probing, vulnerability scanners, bursts of 404/403, login brute force) and bans offending IPs host-wide or at the HTTP layer.

    Two working setups:

    • Host-level crowdsec-firewall-bouncer-nftables (CrowdSec against SSH brute force): install the crowdsecurity/nginx collection and point acquis.d/nginx.yaml at /var/log/nginx/*.log. Drops packets across all server ports with zero overhead on nginx workers; do not use it behind Cloudflare (you cannot block visitor IPs at the packet layer there).
    • crowdsec-nginx-bouncer (or Cloudflare bouncer) (CrowdSec with Traefik behind Cloudflare): enforces bans at the HTTP layer after realip, so it sees the true visitor IP behind a CDN and can return 403 or a CAPTCHA to that specific client.

    How to check

    1. Validate syntax and reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify real IP restoration from a trusted proxy address:
      curl -s -H "Host: sec.example.org" -H "CF-Connecting-IP: 198.51.100.77" http://127.0.0.1/
      # 198.51.100.77 should appear in access.log and $remote_addr
    3. Verify limit_req triggers on a real route (no return 200):
      for i in 1 2 3 4 5; do curl -s -o /dev/null -w "%{http_code} " https://app.example.org/login; done
      # 200 200 200 200 429
    4. Verify auth_request rejects unauthenticated requests:
      curl -s -o /dev/null -w "no-auth:%{http_code}\n" https://app.example.org/admin/
      # no-auth:401

    If it doesn’t work

    After enabling limit_req, every visitor behind Cloudflare starts hitting 429

    Cause
    Without realip, nginx sees Cloudflare edge IPs on every request and counts one shared rate limit per CDN node.
    Fix
    Add trusted Cloudflare subnets to set_real_ip_from and set real_ip_header CF-Connecting-IP; so $binary_remote_addr in limit_req_zone tracks the real visitor IP.

    Testing limit_req or auth_request in a location with a stub return 200 "ok"; never triggers the limit

    Cause
    return runs in the rewrite phase — before the access phase where limit_req, allow/deny, auth_basic, and auth_request execute (Config anatomy).
    Fix
    Test rate limits and auth against a real location backed by proxy_pass or static files (try_files), without return 200.

    A regular browser loading a page with 15 images immediately gets 429 Too Many Requests

    Cause
    limit_req was set to rate=5r/s with no burst (or burst=1), so parallel asset fetches hit the cap at once.
    Fix
    Add a burst queue (burst=20 nodelay;) on general routes, and keep tight limits (rate=5r/m, burst=3) scoped to /login and /api/auth.

    auth_request always returns 500 Internal Server Error even though the auth service replies 403

    Cause
    auth_request accepts only 2xx (allow), 401, and 403 (deny) from the subrequest. Any other code (302, 404, 502) turns into 500.
    Fix
    Check /var/log/nginx/error.log and confirm the auth service is reachable at the location = /_auth address and responds with 200, 401, or 403.

    With auth_basic, the browser loops the password prompt and error.log shows open() "/etc/nginx/.htpasswd" failed (13: Permission denied)

    Cause
    The password file was created as root with mode 600, so the nginx worker user cannot read it.
    Fix
    Fix group ownership and permissions: sudo chown root:nginx /etc/nginx/.htpasswd && sudo chmod 640 /etc/nginx/.htpasswd.