Nginx Log Analyzer Shell Script (Top IPs, URLs & Status Codes)

nginx log analyzer script

Analyze Nginx access logs with a Bash script to find top visitors, URLs, status codes, and 404 errors.

What this script does

  • Parses standard Nginx combined log format
  • Reports top 10 IP addresses and requested URLs
  • Shows HTTP status code breakdown
  • Lists top 404 not-found pages
  • Works on rotated .gz logs

Prerequisites

  • Nginx access log at /var/log/nginx/access.log
  • Standard combined log format
  • gzip support for rotated logs

Step 1: Save the script

sudo nano /usr/local/bin/nginx-log-analyzer.sh
sudo chmod +x /usr/local/bin/nginx-log-analyzer.sh

Step 2: Full script (scroll to read)

nginx-log-analyzer.sh
#!/usr/bin/env bash
set -euo pipefail

LOG_FILE="/var/log/nginx/access.log"
LINES=0                          # 0 = full file

read_log(){
  if [[ "$LOG_FILE" == *.gz ]]; then zcat "$LOG_FILE"; else cat "$LOG_FILE"; fi
}

TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT

if (( LINES > 0 )); then read_log | tail -n "$LINES" > "$TMP"; else read_log > "$TMP"; fi

echo "=== Nginx Log Analysis: $LOG_FILE ==="
echo
echo "--- Top 10 IP addresses ---"
awk '{print $1}' "$TMP" | sort | uniq -c | sort -rn | head -10
echo
echo "--- Top 10 URLs ---"
awk -F'"' '{print $2}' "$TMP" | awk '{print $2}' | sort | uniq -c | sort -rn | head -10
echo
echo "--- HTTP status codes ---"
awk '{print $9}' "$TMP" | sort | uniq -c | sort -rn
echo
echo "--- Top 404 pages ---"
awk '$9==404 {print $7}' "$TMP" | sort | uniq -c | sort -rn | head -10

Scroll inside the box to read the full script.

Step 3: Configure settings

  • LOG_FILE — path to access.log
  • LINES — analyze last N lines (0 = entire file)
  • USE_GZ — set true for compressed logs
Nginx log analyzer shell script output on Linux
Nginx log analyzer shell script output on Linux

Step 4: Test manually

sudo /usr/local/bin/nginx-log-analyzer.sh
sudo tail -100 /var/log/nginx/access.log

Schedule with cron

sudo crontab -e

Add:

0 6 * * 1 /usr/local/bin/nginx-log-analyzer.sh | mail -s 'Weekly Nginx Report' [email protected]

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).