BASH

Filter and Count HTTP Error Codes from Nginx Access Logs

Quickly analyze Nginx access logs to identify and count specific HTTP error codes (e.g., 4xx, 5xx) using `grep`, `awk`, and `sort` for web server monitoring.

#!/bin/bash

LOG_FILE="/var/log/nginx/access.log"

# Check if log file exists
if [ ! -f "$LOG_FILE" ]; then
    echo "Error: Log file $LOG_FILE not found."
    exit 1
fi

echo "Analyzing HTTP error codes (4xx and 5xx) in $LOG_FILE..."

grep -E '" (4[0-9]{2}|5[0-9]{2}) ' "$LOG_FILE" | \
    awk '{print $9}' | \
    sort | \
    uniq -c | \
    sort -nr

if [ $? -eq 0 ]; then
    echo "
Analysis complete."
else
    echo "
An error occurred during analysis."
fi
How it works: This script processes an Nginx access log to find and count occurrences of HTTP 4xx and 5xx error codes. It uses `grep` to filter lines containing these status codes, `awk` to extract the status code field, `sort` to group identical codes, `uniq -c` to count unique occurrences, and finally `sort -nr` to display the most frequent errors first. This provides a quick overview of server-side and client-side errors in your web application.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs