Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations
27 min read

Troubleshooting Nginx Access Log Spikes: Identify Abnormal URIs & Bot Traffic

A comprehensive guide for operations engineers to diagnose and mitigate Nginx access log spikes by analyzing high-frequency URIs, IPs, User-Agents, and status codes, with step-by-step commands for blocking malicious traffic, rate limiting, log filtering, and long-term protection strategies.

Problem Background

Production Nginx access logs suddenly surge, causing disk space alerts, slow log rotation, analysis tool lag, and even impact on normal business log writes. Common scenarios include:

Crawlers suddenly increasing scrape frequency

Malicious scanners attempting path traversal

Abnormal CDN origin-pull traffic

Internal interfaces misused generating massive invalid requests

New business features triggering loop calls

Third-party monitoring or health checks misconfigured

Log spikes consume disk and I/O, affect log analysis, monitoring alerts, audit trails, and may cause service unavailability due to disk exhaustion.

This article targets junior to mid-level ops engineers and system administrators, providing a complete troubleshooting path, analysis methods, filtering strategies, and protection measures to quickly locate abnormal traffic sources and restore log system health.

Applicable Scenarios

Abnormal Nginx log file growth rate

access.log growing several GB or tens of GB in short time

Rapid disk space decline

Log rotation scripts taking too long

ELK or other log analysis systems experiencing delays or blocking

Need to quickly identify high-frequency URIs, IPs, User-Agents

Need to distinguish normal user traffic from crawler traffic

Need to temporarily or permanently block abnormal sources

Core Knowledge Points

Nginx Access Log Format

Standard Nginx access.log format typically:

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

Key field meanings: $remote_addr: Client IP $time_local: Request time $request: Request method, URI, protocol version $status: HTTP status code $body_bytes_sent: Response body bytes $http_user_agent: User-Agent string $http_x_forwarded_for: Proxy chain IPs

Common Root Causes of Log Spikes

Crawler traffic : Search engine crawlers, content aggregation crawlers, data collection crawlers

Scanners : Vulnerability scanning, path traversal, weak password attempts

DDoS attacks : HTTP Flood, Slowloris

Business logic issues : Dead loop requests, retry storms, overly frequent polling

CDN origin-pull anomalies : Cache expiration, origin server misconfiguration

Monitoring probes : Excessive health check frequency, monitoring script misconfiguration

Analysis Dimensions

URI dimension : Which paths are high-frequency accessed

IP dimension : Which IPs initiate massive requests

User-Agent dimension : Which client types have abnormal proportions

Status code dimension : Proportion of abnormal codes like 404, 403, 500

Time dimension : Request volume distribution over time

Response body size : Whether large file downloads or oversized API responses exist

Overall Troubleshooting Approach

Confirm phenomenon : Check log file size, disk usage, growth rate

Quick locate : Find high-frequency URIs, IPs, User-Agents

Classify & judge : Distinguish normal traffic, crawler traffic, malicious traffic

Temporary mitigation : Rate limit or block confirmed abnormal sources

Deep analysis : Combine business logs, application logs, monitoring metrics to locate root cause

Long-term protection : Configure access control, rate limiting strategies, log filtering rules

Verify effectiveness : Observe log growth rate, disk usage, business impact

Postmortem summary : Record problem cause, handling process, protection measures

Practical Steps

Step 1: Confirm Log Spike Phenomenon

Check current log file size

ls -lh /var/log/nginx/access.log

Expected output example:

-rw-r--r-- 1 www-data www-data 8.3G Sep  3 14:25 /var/log/nginx/access.log

If file size is GB-level and still growing rapidly, immediate investigation needed.

Check log directory total usage

du -sh /var/log/nginx/

Output example: 15G /var/log/nginx/ If log directory usage exceeds expectations, check for multiple unrotated historical logs.

Real-time observe log growth rate

watch -n 1 "ls -lh /var/log/nginx/access.log"

Observe file size changes; if growing several MB per second, request volume is abnormal.

Check disk space

df -h /var/log

Output example:

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        50G   45G  2.5G  95% /

If disk usage exceeds 90%, prioritize cleanup or expansion.

Risk warning : If disk space insufficient, Nginx may fail to write logs, causing log loss or service anomalies. Before cleaning logs, ensure backup or offload to other storage.

Step 2: Quick Statistics on Log Lines & Time Range

Count total log lines

wc -l /var/log/nginx/access.log

Output example: 12847563 /var/log/nginx/access.log. Record current line count for later comparison.

View earliest and latest request times

head -n 1 /var/log/nginx/access.log | awk '{print $4, $5}'
tail -n 1 /var/log/nginx/access.log | awk '{print $4, $5}'

Output example:

[03/Sep/2026:10:15:23 +0800]
[03/Sep/2026:14:32:47 +0800]

Confirm log coverage time range, judge when spike occurred.

Count requests in last 10 minutes

awk -v cutoff="$(date -d '10 minutes ago' '+%d/%b/%Y:%H:%M:%S')" '$4 > "["cutoff {count++} END {print count}' /var/log/nginx/access.log

If last 10 minutes requests exceed 50% of total, spike just happened.

Step 3: Find High-Frequency URIs

Top 20 most requested URIs

awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

234567 /api/v1/user/info
 198234 /static/js/app.min.js
 156789 /health
  98765 /api/v1/search?q=test
  87654 /robots.txt
  76543 /favicon.ico
  65432 /.env
  54321 /admin/login
  43210 /wp-admin/
  32109 /phpmyadmin/

Judgment logic : /health, /favicon.ico, /robots.txt high frequency is normal /api/v1/user/info high frequency may be normal if business volume large /.env, /admin/login, /wp-admin/, /phpmyadmin/ high frequency indicates scanner probing /static/js/app.min.js high frequency may be CDN cache expiration or frontend resource abuse

Top interfaces excluding static resources

awk '$7 !~ /\.(css|js|jpg|jpeg|png|gif|ico|woff|woff2|ttf|svg)$/ {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

234567 /api/v1/user/info
 156789 /health
  98765 /api/v1/search?q=test
  65432 /.env
  54321 /admin/login
  43210 /wp-admin/
  32109 /phpmyadmin/
  21098 /api/v1/list
  19876 /index.php
  18765 /config.php

Next actions :

If /api/v1/user/info proportion too high, check for client polling too fast

If /.env, /admin/login etc. high frequency, immediately block scanner IPs

If /health high frequency, check monitoring system configuration

High-frequency requests with query parameters

awk '$7 ~ /\?/ {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

98765 /api/v1/search?q=test
  45678 /api/v1/search?q=admin
  34567 /api/v1/search?q=SELECT
  23456 /index.php?s=/Index/\think\app/invokefunction
  12345 /api/v1/user?id=1

If query parameters contain SQL keywords, function call paths, indicates injection attempts or vulnerability probing.

Step 4: Find High-Frequency IPs

Top 20 requesting IPs

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

345678 192.168.1.100
 198765 203.0.113.45
 156789 198.51.100.23
  98765 192.0.2.56
  87654 10.0.0.5

Judgment logic :

If single IP requests exceed 10% of total, focus attention

If IP is internal (10.x, 172.16.x, 192.168.x), check internal services or monitoring systems

If IP is public, query IP ownership and reputation

Query IP ownership

whois 203.0.113.45 | grep -i "country\|netname\|descr"

Or use online service:

https://ipinfo.io/203.0.113.45

Count distinct URIs per IP

awk '{print $1, $7}' /var/log/nginx/access.log | sort -u | awk '{print $1}' | uniq -c | sort -rn | head -20

Output example:

12345 203.0.113.45
  5678 198.51.100.23
  3456 192.0.2.56

If single IP accesses many different URIs, likely crawler or scanner.

Request time distribution for single IP

grep "203.0.113.45" /var/log/nginx/access.log | awk '{print $4}' | cut -d: -f2 | sort | uniq -c

Output example:

1234 10
  2345 11
  3456 12
  4567 13

If requests concentrate in short time bursts, indicates automated tool.

Step 5: Find High-Frequency User-Agents

Top 20 User-Agents

awk -F" '{print $6}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

234567 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
 198765 Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
 156789 python-requests/2.28.1
  98765 Go-http-client/1.1
  87654 curl/7.68.0
  76543 -
  65432 Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)
  54321 Scrapy/2.7.1 (+https://scrapy.org)

Judgment logic : Googlebot, Baiduspider are normal search engine crawlers python-requests, Go-http-client, curl are automation scripts Scrapy is open-source crawler framework - or empty string means client didn't set User-Agent, possibly malicious tool

Crawler traffic proportion

total=$(wc -l < /var/log/nginx/access.log)
bot=$(awk -F" '$6 ~ /bot|spider|crawler|scrape/i {count++} END {print count}' /var/log/nginx/access.log)
echo "Total: $total, Bot: $bot, Ratio: $(echo "scale=2; $bot*100/$total" | bc)%"

Output example: Total: 12847563, Bot: 3845678, Ratio: 29.93%. If crawler traffic exceeds 30%, need targeted rate limiting.

Empty User-Agent requests

awk -F" '$6 == "-" || $6 == "" {count++} END {print count}' /var/log/nginx/access.log

Output example: 76543. Empty User-Agent usually malicious tools or misconfigured clients.

Step 6: Analyze Status Code Distribution

Status code distribution

awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

Output example:

8765432 200
 2345678 404
  987654 304
  345678 403
  123456 500
   98765 301
   45678 502

Judgment logic :

High 200 proportion is normal

High 404 indicates path probing or dead links

High 403 indicates access control triggered

High 500/502/503 indicates backend service anomalies

High 301/302 check redirect configuration

Top 404 URIs

awk '$9 == 404 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

65432 /.env
  54321 /admin/login
  43210 /wp-admin/
  32109 /phpmyadmin/
  21098 /.git/config
  19876 /config.php

High-frequency 404 paths usually scanner probes; block source IPs.

Top 5xx error URIs

awk '$9 >= 500 && $9 < 600 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

Output example:

12345 /api/v1/report
   5678 /api/v1/export
   3456 /api/v1/generate

5xx errors indicate backend processing anomalies; check application logs and performance metrics.

Step 7: Analyze Time Dimension

Hourly request count

awk '{print $4}' /var/log/nginx/access.log | cut -d: -f2 | sort | uniq -c

Output example:

123456 10
  234567 11
  345678 12
 4567890 13
  345678 14

If certain hour far exceeds others, record that time for further analysis.

Minute-level request count for abnormal hour

awk '$4 ~ /03\/Sep\/2026:13:/ {print $4}' /var/log/nginx/access.log | cut -d: -f2,3 | sort | uniq -c

Output example:

1234 13:00
  2345 13:01
  3456 13:02
 456789 13:03
  3456 13:04

Pinpoint exact minute of traffic spike.

Extract spike period log sample

awk '$4 ~ /03\/Sep\/2026:13:03/ {print}' /var/log/nginx/access.log > /tmp/spike_sample.log

Analyze sample logs in detail.

Step 8: Comprehensive Analysis to Determine Root Cause

Analyze IP, URI, User-Agent combinations in sample

awk '{print $1, $7, $6}' /tmp/spike_sample.log | sort | uniq -c | sort -rn | head -20

Output example:

123456 203.0.113.45 /api/v1/user/info python-requests/2.28.1
  98765 198.51.100.23 /health Go-http-client/1.1
  76543 192.0.2.56 /.env curl/7.68.0

Root cause judgment :

Single IP + single URI + automation tool: possible internal script misconfiguration

Single IP + multiple URIs + crawler UA: normal crawler behavior

Multiple IPs + sensitive URIs + empty UA: scanner cluster attack

Multiple IPs + normal URIs + normal UAs: possible CDN origin-pull or business peak

Check for loop requests

awk '{print $7}' /tmp/spike_sample.log | sort | uniq -c | sort -rn | head -5

If certain URI requested tens of thousands times by same IP in short period, check:

Client retry logic errors

Loop redirects

Dead loop polling

Check response body size

awk '{sum+=$10; count++} END {print "Avg:", sum/count, "Total:", sum}' /tmp/spike_sample.log

Output example: Avg: 1024 Total: 456789123. If average response body too large, check for large file downloads or abnormal API response sizes.

Step 9: Temporary Mitigation Measures

Based on analysis, apply targeted rate limiting or blocking.

Block single IP

Add to Nginx config:

# /etc/nginx/conf.d/block_ip.conf
deny 203.0.113.45;

Reload config: nginx -t && nginx -s reload Risk warning : If IP is CDN node or proxy, may block legitimate users. Combine with $http_x_forwarded_for to determine real IP.

Block IP range

deny 203.0.113.0/24;

Batch block IPs

Generate IP list:

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -50 | awk '$1 > 100000 {print "deny " $2 ";"}'

Output example:

deny 203.0.113.45;
deny 198.51.100.23;
deny 192.0.2.56;

Append to /etc/nginx/conf.d/block_ip.conf and reload.

Verification : curl -I http://your-domain.com --interface 203.0.113.45 should return 403 Forbidden.

Block specific User-Agents

Using map (safer than if in location):

# /etc/nginx/conf.d/block_ua_map.conf
map $http_user_agent $block_ua {
    default 0;
    ~*python-requests 1;
    ~*scrapy 1;
    ~*curl 1;
}

server {
    if ($block_ua) {
        return 403;
    }
}

Block specific URIs

location ~ /\.(env|git|svn) {
    deny all;
}

location ~ /(phpmyadmin|wp-admin|admin) {
    deny all;
}

Limit request rate per IP

Use limit_req module:

# /etc/nginx/nginx.conf
http {
    limit_req_zone $binary_remote_addr zone=global:10m rate=10r/s;
    server {
        location / {
            limit_req zone=global burst=20 nodelay;
        }
    }
}

Parameters: rate=10r/s (max 10 req/s), burst=20 (allow burst 20), nodelay (immediate 503 when exceeded).

Rate limit specific URI

location /api/v1/user/info {
    limit_req zone=api burst=50 nodelay;
}

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

Step 10: Log Filtering & Rotation Optimization

Configure Nginx to not log specific requests

In server block:

# Don't log health checks
location /health {
    access_log off;
    return 200 "OK
";
}

# Don't log static resources
location ~* \.(css|js|jpg|jpeg|png|gif|ico|woff|woff2|ttf|svg)$ {
    access_log off;
    expires 30d;
}

# Don't log favicon and robots.txt
location = /favicon.ico {
    access_log off;
    log_not_found off;
}
location = /robots.txt {
    access_log off;
    log_not_found off;
}

Verification : Access /health then check log: tail -f /var/log/nginx/access.log | grep "/health" should have no output.

Conditional logging with map

# /etc/nginx/nginx.conf
http {
    map $request_uri $loggable {
        default 1;
        ~^/health 0;
        ~\.(css|js|jpg|jpeg|png|gif|ico)$ 0;
    }
    server {
        access_log /var/log/nginx/access.log main if=$loggable;
    }
}

Note : access_log ... if= syntax supported in Nginx 1.7.0+; older versions need upgrade or alternative.

Optimize log rotation strategy

Edit /etc/logrotate.d/nginx:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi
    endscript
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

Key parameters: daily (rotate daily), rotate 7 (keep 7 days), compress (compress old logs), delaycompress (delay compression), postrotate (send USR1 to reopen log file).

Verification : Manual trigger: logrotate -f /etc/logrotate.d/nginx. Check ls -lh /var/log/nginx/ for access.log.1 etc.

Emergency manual log cleanup

Risk warning : Direct deletion may cause Nginx write failure; use correct method.

Wrong way : rm /var/log/nginx/access.log Correct ways :

# Method 1: Truncate file
> /var/log/nginx/access.log

# Method 2: Move and recreate
mv /var/log/nginx/access.log /var/log/nginx/access.log.bak
touch /var/log/nginx/access.log
chown www-data:adm /var/log/nginx/access.log
chmod 640 /var/log/nginx/access.log
nginx -s reopen

Verification : ls -lh /var/log/nginx/access.log and tail -f /var/log/nginx/access.log. Send test request to confirm normal logging.

Step 11: Long-Term Protection Strategies

Deploy WAF or anti-crawler modules

Recommended: ModSecurity (open-source WAF with OWASP CRS), Naxsi (lightweight WAF), lua-resty-waf (OpenResty-based), cloud vendor WAFs (Alibaba Cloud, Tencent Cloud, AWS).

Configure Nginx rate limiting

Global rate limiting:

http {
    limit_req_zone $binary_remote_addr zone=global:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;
    limit_req_zone $binary_remote_addr zone=static:10m rate=50r/s;
    limit_conn_zone $binary_remote_addr zone=conn:10m;
    server {
        limit_conn conn 20;
        location /api/ {
            limit_req zone=api burst=50 nodelay;
        }
        location /static/ {
            limit_req zone=static burst=100 nodelay;
        }
        location / {
            limit_req zone=global burst=20 nodelay;
        }
    }
}

Configure robots.txt

location = /robots.txt {
    root /var/www/html;
    access_log off;
}

Create /var/www/html/robots.txt:

User-agent: *
Disallow: /admin/
Disallow: /api/internal/
Crawl-delay: 10

User-agent: Googlebot
Allow: /

User-agent: Baiduspider
Crawl-delay: 5

Note : robots.txt only effective for compliant crawlers; malicious crawlers ignore.

Configure access control

# Restrict admin to internal network
location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
}

# Require auth for API
location /api/ {
    auth_request /auth;
}
location = /auth {
    internal;
    proxy_pass http://auth-service;
}

Configure log sampling

For ultra-high-frequency requests, sample logging (requires OpenResty or Nginx+Lua):

location / {
    access_by_lua_block {
        if math.random(100) <= 10 then
            ngx.var.sample = "1"
        else
            ngx.var.sample = "0"
        end
    }
    access_log /var/log/nginx/access.log main if=$sample;
}

Deploy log analysis & alerting system

Recommended: ELK Stack (Elasticsearch+Logstash+Kibana), EFK Stack (Elasticsearch+Fluentd+Kibana), Loki+Grafana (lightweight), Graylog (open-source log management).

Alert rules: log growth rate threshold, single IP request threshold, 404/403/5xx proportion threshold, specific URI traffic spike.

Step 12: Verification & Observation

Verify blocking rules

# Test blocked IP
curl -I -x http://203.0.113.45 http://your-domain.com
# Test blocked URI
curl -I http://your-domain.com/.env
# Test blocked User-Agent
curl -I -A "python-requests/2.28.1" http://your-domain.com

Expected: 403 Forbidden.

Verify rate limiting

for i in {1..30}; do
    curl -I http://your-domain.com/api/v1/user/info
    sleep 0.1
done

Expected: some requests return 503 Service Temporarily Unavailable.

Observe log growth rate

before=$(stat -c%s /var/log/nginx/access.log)
sleep 60
after=$(stat -c%s /var/log/nginx/access.log)
rate=$((($after - $before) / 60))
echo "Growth rate: $rate bytes/sec"

If growth rate returns to normal (typically < 100 KB/s), mitigation effective.

Observe request volume changes

while true; do
    date
    tail -n 1000 /var/log/nginx/access.log | wc -l
    sleep 10
done

Or use ngxtop for real-time monitoring:

pip install ngxtop && ngxtop -l /var/log/nginx/access.log

Observe disk space

watch -n 10 "df -h /var/log"

Confirm disk space no longer rapidly declining.

Observe business impact

Check application logs: normal user requests unaffected

Check monitoring metrics: response time, error rate normal

Collect user feedback: no false positives

Step 13: Deep Analysis & Root Cause Location

Combine with application logs

If Nginx shows abnormal interface requests, check app logs:

grep "/api/v1/user/info" /var/log/app/app.log | tail -100

Look for exceptions, slow queries, resource exhaustion.

Combine with database logs

If database suspected bottleneck, check slow query log:

tail -100 /var/log/mysql/slow.log
mysqldumpslow -s c -t 10 /var/log/mysql/slow.log

Combine with monitoring metrics

Check Prometheus, Grafana, or cloud monitoring for:

Nginx metrics : QPS, response time, error rate, connections

System metrics : CPU, memory, disk I/O, network bandwidth

Application metrics : API response time, DB connections, cache hit rate

Business metrics : User activity, order volume, payment volume

Packet capture analysis

If network-layer attack suspected, use tcpdump:

tcpdump -i eth0 -w /tmp/capture.pcap port 80 or port 443

Analyze with Wireshark for SYN Flood, HTTP Flood, Slowloris, excessive retransmissions.

Check CDN origin-pull configuration

If using CDN, verify:

Cache rules correctness

Origin Host correctness

Cache penetration (massive cache misses)

Cache avalanche

Check business logic

If loop requests from business logic:

Check client retry logic

Check polling intervals

Check for dead loops

Check for recursive calls

Step 14: Rollback Plan

Rollback blocking rules

vi /etc/nginx/conf.d/block_ip.conf
# Comment or delete deny lines
nginx -t && nginx -s reload

Rollback rate limiting rules

vi /etc/nginx/nginx.conf
# Comment limit_req and limit_conn lines
nginx -t && nginx -s reload

Rollback log filtering rules

vi /etc/nginx/nginx.conf
# Remove access_log off or if=$loggable
nginx -t && nginx -s reload

Emergency rollback all config

# Backup current config
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.$(date +%Y%m%d%H%M%S)
cp -r /etc/nginx/conf.d /etc/nginx/conf.d.$(date +%Y%m%d%H%M%S)

# Restore backup
cp /etc/nginx/nginx.conf.bak /etc/nginx/nginx.conf
cp -r /etc/nginx/conf.d.bak/* /etc/nginx/conf.d/
nginx -t && nginx -s reload

Risk warning : Backup before rollback to avoid unrecoverable state.

Common Commands Summary

Log Analysis Commands

# Count log lines
wc -l /var/log/nginx/access.log

# Top URIs
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# Top IPs
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# Top User-Agents
awk -F" '{print $6}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# Status code distribution
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

# Top 404 URIs
awk '$9 == 404 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# Hourly request count
awk '{print $4}' /var/log/nginx/access.log | cut -d: -f2 | sort | uniq -c

# Real-time monitor
tail -f /var/log/nginx/access.log

# Real-time QPS
tail -f /var/log/nginx/access.log | pv -l -i 1 -r > /dev/null

Config Management Commands

# Test config
nginx -t
# Reload config
nginx -s reload
# View version & compile params
nginx -V
# View processes
ps aux | grep nginx
# View listening ports
ss -tlnp | grep nginx

Disk Management Commands

# Disk space
df -h /var/log
# Directory usage
du -sh /var/log/nginx/
# Largest files
du -ah /var/log/nginx/ | sort -rh | head -10
# Real-time disk monitor
watch -n 10 "df -h /var/log"

Log Rotation Commands

# Manual rotate
logrotate -f /etc/logrotate.d/nginx
# Test config
logrotate -d /etc/logrotate.d/nginx
# View status
cat /var/lib/logrotate/status | grep nginx

Configuration Examples

Complete Nginx Rate Limiting & Access Control Config

See /etc/nginx/nginx.conf, /etc/nginx/conf.d/default.conf, /etc/nginx/conf.d/block_ip.conf in article for full examples including: user, worker_processes, events, http block with log_format, gzip, limit_req_zone, limit_conn_zone, map for UA blocking, server block with health check, static resources, robots.txt, favicon, sensitive path blocking, API rate limiting, proxy settings, upstream backend.

Logrotate Config

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    prerotate
        if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
            run-parts /etc/logrotate.d/httpd-prerotate; \
        fi
    endscript
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
    size 1G
    maxage 14
}

Log & Metrics Observation Methods

Nginx Built-in Status Page

Enable stub_status module:

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    allow 192.168.1.0/24;
    deny all;
}

Access: curl http://127.0.0.1/nginx_status. Output fields: Active connections, accepts, handled, requests, Reading, Writing, Waiting.

Prometheus Monitoring for Nginx

Install nginx-prometheus-exporter, configure scrape from /nginx_status. Key metrics: nginx_connections_active, nginx_connections_reading, nginx_connections_writing, nginx_connections_waiting, nginx_http_requests_total.

mtail for Log Parsing & Metrics Export

Install mtail, create /etc/mtail/nginx.mtail with regex to extract status, method, URI, request_time. Run mtail, configure Prometheus to scrape port 3903.

Grafana Visualization

Import dashboards: ID 12708 (Nginx Prometheus Exporter), ID 11199 (Nginx Log Exporter). Key panels: Request QPS, Response time distribution, Status code distribution, Active connections, Error rate, Traffic bandwidth.

Troubleshooting Paths

Path 1: Log Spike → High-Freq URI → Business Logic Issue

Stat high-freq URIs

Check if normal business interface

Check app logs for call source

Check client code for loop calls or retry errors

Fix client code or optimize interface

Configure rate limiting to prevent recurrence

Path 2: Log Spike → High-Freq IP → Crawler Traffic

Stat high-freq IPs

Query IP ownership & reputation

Check User-Agent for crawler confirmation

Check robots.txt for crawler permission

If malicious crawler, block IP or range

If normal but high frequency, configure rate limiting

Configure log filtering to not log crawler requests

Path 3: Log Spike → High-Freq 404 → Scanner Probing

Stat 404 high-freq URIs

Confirm sensitive paths ( .env, wp-admin, phpmyadmin)

Stat requesting IPs

Block scanner IPs or ranges

Configure Nginx to block sensitive paths

Configure log filtering to not log 404 scans

Deploy WAF protection

Path 4: Log Spike → Health Check Over-frequency → Monitoring Misconfig

Stat /health request volume

Check monitoring system config for probe frequency

Check Kubernetes LivenessProbe/ReadinessProbe

Check load balancer health check config

Adjust probe frequency or timeout

Configure Nginx to not log health checks

Path 5: Log Spike → CDN Origin-Pull Anomaly → Cache Config Issue

Stat request source IPs, confirm CDN nodes

Check CDN cache rules

Check Nginx cache response headers ( Cache-Control, Expires)

Check for cache penetration (massive cache misses)

Optimize cache rules, increase hit rate

Configure origin rate limiting to prevent CDN overload

Risk Warnings

IP Blocking Risks

Blocking CDN node IP affects all users via that node

Blocking company egress IP affects all employees

Blocking ISP NAT gateway affects many regular users

Recommendations : Prefer rate limiting over blocking; combine with $http_x_forwarded_for for real IP; set blocking expiry, review periodically; record blocking reason for traceability.

Rate Limiting Risks

Overly strict limiting affects normal users

Misconfigured rules may block all requests

Burst traffic may trigger limiting, impacting business

Recommendations : Set thresholds based on business baseline; use burst for bursts; differentiate limits per interface; canary release rules, observe impact.

Log Filtering Risks

Misconfigured filters may drop all logs

Over-filtering prevents issue tracing

Not logging affects audit & compliance

Recommendations : Only filter clear low-value logs (health checks, static resources); retain business API logs; retain abnormal status codes (4xx, 5xx); periodically review filter rules.

Log Cleanup Risks

Direct deletion may break Nginx writing

Over-cleanup loses historical tracing

Improper cleanup affects audit & compliance

Recommendations : Use logrotate for auto rotation, not manual delete; emergency truncate with > file not rm; backup or offload to object storage before cleanup; retain at least 7 days logs for troubleshooting.

Verification Methods

Verify Blocking Rules

# Test blocked IP
curl -I -x http://203.0.113.45 http://your-domain.com
# Expected 403 Forbidden

# Test blocked URI
curl -I http://your-domain.com/.env
# Expected 403 Forbidden

# Test blocked User-Agent
curl -I -A "python-requests/2.28.1" http://your-domain.com
# Expected 403 Forbidden

Verify Rate Limiting

for i in {1..30}; do
    curl -I http://your-domain.com/api/v1/user/info
    sleep 0.1
done
# Expect some 503 or 429

# ab stress test
ab -n 1000 -c 10 http://your-domain.com/
# Observe success/failure rates

Verify Log Filtering

curl http://your-domain.com/health
tail -f /var/log/nginx/access.log | grep "/health"
# Expect no output

Verify Log Rotation

logrotate -f /etc/logrotate.d/nginx
ls -lh /var/log/nginx/
# Expect access.log.1.gz etc.
echo "test" | logger -t nginx
tail -1 /var/log/nginx/access.log

Verify Nginx Config

nginx -t
# Expect: syntax ok, test successful
ps aux | grep nginx
# Expect master and worker processes
ss -tlnp | grep nginx
# Expect port 80 or 443

Rollback Plans

Quick Config Rollback

timestamp=$(date +%Y%m%d%H%M%S)
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.$timestamp
cp -r /etc/nginx/conf.d /etc/nginx/conf.d.$timestamp

# Restore previous backup
ls -lt /etc/nginx/nginx.conf.* | head -2 | tail -1 | awk '{print $NF}' | xargs -I {} cp {} /etc/nginx/nginx.conf
nginx -t && nginx -s reload
# If fails, restore earlier backup similarly

Rollback Rate Limiting

sed -i 's/^    limit_req/#    limit_req/g' /etc/nginx/nginx.conf
sed -i 's/^    limit_conn/#    limit_conn/g' /etc/nginx/nginx.conf
nginx -t && nginx -s reload

# Restore
sed -i 's/^#    limit_req/    limit_req/g' /etc/nginx/nginx.conf
sed -i 's/^#    limit_conn/    limit_conn/g' /etc/nginx/nginx.conf
nginx -t && nginx -s reload

Rollback Blocking Rules

> /etc/nginx/conf.d/block_ip.conf
nginx -s reload

# Restore
cp /etc/nginx/conf.d/block_ip.conf.$timestamp /etc/nginx/conf.d/block_ip.conf
nginx -s reload

Emergency Rollback to Default

mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.broken
cp /usr/share/nginx/conf/nginx.conf.default /etc/nginx/nginx.conf
nginx -t && nginx -s reload
# If default missing, reinstall: apt-get install --reinstall nginx-common or yum reinstall nginx

Production Environment Considerations

Pre-Change Checks

Backup config : All changes must be backed up

Test env validation : Verify config correctness in test environment first

Canary release : If multiple Nginx, validate on one then roll out

Off-peak operation : Choose low-traffic window (e.g., early morning)

Notify stakeholders : Inform business, monitoring, ops teams in advance

During-Change Monitoring

Real-time log watch : tail -f /var/log/nginx/access.log Real-time error log watch : tail -f /var/log/nginx/error.log Real-time metrics watch : QPS, response time, error rate

Real-time business metrics : Order volume, payment success rate

Rollback ready : Prepared to rollback config anytime

Post-Change Verification

Functional verification : Access key pages/APIs, confirm normal

Performance verification : Confirm no significant response time degradation

Log verification : Confirm log format correct, content complete

Monitoring verification : Confirm metrics normal

User feedback : Collect feedback, confirm no anomalies

Permission Control

Least privilege : Log files 640, owner www-data

Config file permissions : 644, owner root

Sensitive config protection : Files with passwords/keys 600

Audit logging : Record all config change operations

Documentation

Change records : Time, operator, content, reason

Rollback records : Time, reason, method

Issue records : Phenomenon, root cause, solution

Config annotations : Comment each config item with purpose and notes

Long-Term Maintenance

Weekly checks : Log size, disk space, monitoring alerts

Monthly optimization : Review blocking rules, rate limits, log filters

Quarterly drills : Practice failure recovery procedures

Timely updates : Update Nginx version, patch security vulnerabilities

Summary

Nginx access log spike issues involve log analysis, traffic identification, access control, rate limiting protection, log management across multiple stages. This article provides a complete solution from problem discovery to root cause location, from temporary mitigation to long-term protection.

Core points:

Quick locate : Prioritize high-frequency URI, IP, User-Agent stats to rapidly identify abnormal sources

Categorized handling : Distinguish normal, crawler, malicious traffic; apply targeted measures

Mitigation first : Temporary block or rate limit to quickly restore log system health

Deep analysis : Combine app logs, monitoring metrics, business logic to locate root cause

Long-term protection : Configure access control, rate limiting strategies, log filtering, log rotation

Risk awareness : All changes must be backed up, tested, canary-released, verified, rollback-ready

Continuous optimization : Periodically review rules, update configs, drill processes

Production operations must be cautious: all destructive operations require backup first, verification second, execution last, ensuring rollback capability. Logs are critical for troubleshooting; do not lightly clean or filter unless impact scope is clearly known.

Commands, configs, and processes in this article are production-validated, but environments may differ; always adjust to actual conditions. When issues arise, first observe phenomena, collect evidence, analyze root cause, then act — avoid blind operations.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion