basforge

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

    RU
    ManualHomelabnginx

    nginx logs, metrics, and debugging: JSON logs, timings, stub_status, and 499/502/504

    Break down the default access.log line, switch to JSON logs with $request_time and $upstream_response_time, filter noise, rotate logs with USR1, expose stub_status metrics, and trace five common failures: 499, 502, 504, 301 loops, and 413.

    Anatomy of an access.log line

    The default main format in /etc/nginx/nginx.conf is compact, yet it omits backend response time. Click any segment to inspect what it logs:

    /var/log/nginx/access.log (main format) · Pick a segment
    The default main format omits $request_time and $upstream_response_time — define a custom format to diagnose slow responses.

    JSON logs with timings, filtering, and buffering

    To pinpoint latency and ship logs to Vector or Loki (Traefik logs), replace the plain text format with JSON using escape=json and four diagnostic variables: $request_time, $upstream_response_time, $upstream_addr, and $upstream_cache_status.

    /etc/nginx/conf.d/06-logging.conf
    log_format json_timing escape=json
        '{"time":"$time_iso8601",'
        '"ip":"$remote_addr",'
        '"method":"$request_method",'
        '"uri":"$request_uri",'
        '"status":$status,'
        '"bytes":$body_bytes_sent,'
        '"req_time":$request_time,'
        '"up_time":"$upstream_response_time",'
        '"up_addr":"$upstream_addr",'
        '"cache":"$upstream_cache_status"}';
    Key part

    escape=json escapes quotes and control characters in URI and User-Agent, keeping JSON valid even when scanners send malformed paths. req_time is total request duration; up_time is time spent waiting on the backend.

    map $uri $loggable {
        /healthz 0;
        default  1;
    }
    
    access_log /var/log/nginx/access.log json_timing buffer=32k flush=5s if=$loggable;

    Drop noise: /healthz probes stay out of the log ($loggable = 0). buffer=32k flush=5s batches disk writes to cut I/O under load.

    Finding the bottleneck from two timings

    $request_time $upstream_response_time What is happening
    0.001 "" (empty) nginx served the response itself (static file or cache HIT)
    4.205 "4.201" The backend app or database behind nginx is slow
    4.205 "0.015" Backend replied immediately — the client connection is slow (slow mobile download)
    0.301 "0.300" (status: 499) Client aborted after 0.3 s while still waiting on the app

    Log rotation (logrotate and USR1)

    The nginx.org package installs /etc/logrotate.d/nginx automatically. Its key piece is postrotate, which sends USR1 to the master process (nginx -s reopen): workers close the rotated descriptor and open the fresh /var/log/nginx/access.log without reloading the config or dropping open connections.

    Basic metrics: stub_status

    --with-http_stub_status_module is compiled into the nginx.org package. Bind it only on 127.0.0.1 for local checks or nginx-prometheus-exporter:

    server {
        listen 127.0.0.1:8081;
        access_log off;
    
        location = /nginx_status {
            stub_status;
        }
    }

    Output of curl -s http://127.0.0.1:8081/nginx_status:

    Active connections: 1
    server accepts handled requests
     41 41 41
    Reading: 0 Writing: 1 Waiting: 0
    • Active connections — all currently open client connections (including Waiting).
    • accepts / handled / requests — accepted connections, handled connections (if handled < accepts, workers hit worker_connections), and total HTTP requests served (requests exceeds handled with keep-alive).
    • Reading — reading request headers, Writing — sending responses or waiting on a backend, Waiting — idle keep-alive connections.

    Five common failures: trace and quick diagnosis

    1. Client✕ dropped conn
    2. nginx✓ logs 499
    3. Backend… still working
    {"time":"2026-11-25T17:51:50+00:00","uri":"/slow","status":499,"bytes":0,"req_time":0.301,"up_time":"0.300","up_addr":"127.0.0.1:8105"}
    Cause

    The client closed the connection before getting a response — either the user closed the tab or an upstream load balancer/client has a timeout shorter than the backend.

    Check with

    Check up_time in the JSON log: if it is high, optimize the slow backend endpoint; if it is 0.05, check the client network or timeout.

    1. Client✓ request sent
    2. nginx✕ refused / drop
    3. Backend✕ not listening
    2026/11/25 17:16:47 [error] connect() failed (111: Connection refused) while connecting to upstream, upstream: "http://127.0.0.1:3000/api"
    Cause

    nginx could not connect to the backend (app crashed, listens on another port, Docker container IP changed, or worker lacks permissions on the PHP-FPM Unix socket).

    Check with

    Run sudo tail -n 20 /var/log/nginx/error.log and sudo ss -ltnp to see if the port or socket is alive.

    1. Client✓ waiting
    2. nginx✕ 60s elapsed
    3. Backend… stuck in DB
    2026/11/25 17:22:10 [error] upstream timed out (110: Connection timed out) while reading response header from upstream
    Cause

    TCP connected, yet the backend sent no response headers within proxy_read_timeout (default 60s).

    Check with

    If the operation is legitimately long (report export, LLM call), raise proxy_read_timeout in that location; otherwise look for locks in the app or database.

    1. Browser✓ HTTPS :443
    2. Cloudflare✕ sends HTTP :80
    3. nginx :80✕ 301 to HTTPS
    HTTP/1.1 301 Moved Permanently
    Location: https://example.org/   # repeats 20 times -> ERR_TOO_MANY_REDIRECTS
    Cause

    Cloudflare SSL is set to Flexible: HTTPS on the outside, plain HTTP on port 80 to your origin, where nginx redirects straight back to HTTPS.

    Check with

    Switch Cloudflare SSL/TLS to Full (strict) and verify with curl -sI https://example.org/.

    1. Client✓ POST 12 MB
    2. nginx✕ 1m limit
    2026/11/25 17:30:02 [error] client intended to send too large body: 12582912 bytes
    Cause

    The request body exceeded client_max_body_size (default 1m), so nginx rejected it before forwarding to the app.

    Check with

    Raise client_max_body_size in the target location (plus upload_max_filesize/post_max_size if PHP sits behind nginx).

    How to check

    1. Confirm the JSON log parses cleanly after a couple of requests:
      sudo tail -n 3 /var/log/nginx/access.log | jq .
    2. Find the slowest backend requests straight from the shell:
      sudo jq -r 'select(.up_time != "") | "\(.up_time)\t\(.status)\t\(.uri)"' /var/log/nginx/access.log \
        | sort -rn | head -n 10
    3. Check stub_status metrics:
      curl -s http://127.0.0.1:8081/nginx_status
    4. Test log reopening after rotation manually:
      sudo nginx -s reopen && sudo ls -l /var/log/nginx/access.log

    If it doesn’t work

    After log rotation the old file is renamed to access.log.1, yet nginx keeps writing to it while the new access.log stays empty

    Cause
    Workers hold an open file descriptor by inode rather than filename: after mv, they keep writing to the old file until signaled with USR1.
    Fix
    Call nginx -s reopen (or kill -USR1 $(cat /run/nginx.pid)) in the postrotate block of /etc/logrotate.d/nginx.

    access.log shows lots of 499 responses while the app logs no errors

    Cause
    499 Client Closed Request is an nginx-specific code: the client (browser, mobile link, or upstream load balancer with a short timeout) closed the connection before the backend finished.
    Fix
    Compare $request_time and $upstream_response_time on 499 lines: if both match (for example 5.001 and 5.000), the app is slow and the client timed out waiting.

    Logs grow by gigabytes per day from /healthz probes, images, and icons

    Cause
    access_log records every request, including health checks firing every second.
    Fix
    Add access_log off; inside location = /healthz or filter entries using a map table with if=$loggable.

    A site behind Cloudflare hits an infinite 301 redirect loop (ERR_TOO_MANY_REDIRECTS)

    Cause
    Cloudflare’s SSL mode is set to Flexible (connecting to your origin over plain HTTP on port 80), while nginx responds with return 301 https://… on every HTTP request.
    Fix
    Switch Cloudflare SSL/TLS mode to Full (strict) so Cloudflare connects over HTTPS on port 443 and validates the certificate.

    Enabling error_log … debug; for troubleshooting filled the disk in minutes

    Cause
    debug logs tens of kilobytes for every request from every visitor on the server.
    Fix
    Instead of global debug, trace only your own IP inside events { debug_connection 203.0.113.50; }.