BASH
Monitor Web Server Access Logs for HTTP Errors
Learn to create a Bash script that continuously monitors your Nginx or Apache access logs for 4xx and 5xx HTTP error codes, useful for immediate issue detection.
#!/bin/bash
# Configuration
LOG_FILE="/var/log/nginx/access.log" # Path to your web server access log (e.g., /var/log/apache2/access.log)
ERROR_CODES="40[0-9]|41[0-9]|42[0-9]|43[0-9]|44[0-9]|45[0-9]|46[0-9]|47[0-9]|48[0-9]|49[0-9]|50[0-9]|51[0-9]|52[0-9]|53[0-9]|54[0-9]|55[0-9]" # Regex for 4xx and 5xx errors
echo "Monitoring $LOG_FILE for HTTP errors (4xx, 5xx). Press Ctrl+C to stop."
# Use tail -f to follow the log file and grep for error codes
tail -f "$LOG_FILE" | grep -E "$ERROR_CODES" --color=always
How it works: This script provides real-time monitoring of a web server's access log for HTTP error codes (4xx and 5xx). It uses `tail -f` to continuously output new lines appended to the log file, which are then piped to `grep -E` (extended regex) to filter for patterns matching common error status codes. `--color=always` highlights the matches, making it easier to spot errors quickly. This is crucial for detecting and responding to website issues promptly.