Error Solutions

Extracting 4xx and 5xx Error URLs from Server Access Logs: A Practical Script Guide

  • 17 min read
  • Hostragons Team
Extracting 4xx and 5xx Error URLs from Server Access Logs: A Practical Script Guide

The script for extracting 4xx and 5xx error URLs from server access logs is a handy analysis tool that automatically lists URLs generating client-side 4xx errors and server-side 5xx errors by reading the web server's access records. With this script, you can quickly identify which pages are returning 404, 403, 500, 502, or 503 errors, allowing you to address SEO losses, waste of crawl budget, broken links, and performance issues promptly.

Finding error URLs on a website cannot solely rely on browsing the site. Some errors may only appear in specific bots, outdated campaign links, API requests, mobile user agents, or during times of high traffic. Access log files contain details about every request to the server, including the date, IP address, method, URL path, HTTP status code, response size, and user-agent information in most configurations. Therefore, log analysis is indispensable for technical SEO, security, and operations teams.

In this guide, we will address a practical bash-based script logic for extracting URLs that return 4xx and 5xx errors from Apache and Nginx access log files, including sample commands, output formats, interpretation methods, and prioritization of fixes step by step. If you have root access on your own server, you can apply it directly; if you're using shared hosting, you can use the same approach on the log files downloaded from your control panel. For reliable hosting infrastructure, explore Hostragons Web Hosting Packages and for projects requiring more control, check out Hostragons VPS Server Solutions.

What is an Access Log and Why is 4xx/5xx Analysis Important?

An access log is a log file that records HTTP requests sent to the web server. In Apache, it is usually found at /var/log/apache2/access.log or /var/log/httpd/access_log, while in Nginx, it is located at /var/log/nginx/access.log. In control panels, these records can be separated by domain. In accounts using cPanel, Plesk, or DirectAdmin, log files can be downloaded as compressed archives.

HTTP status codes classify the result of a request. 2xx indicates successful responses, 3xx indicates redirects, 4xx represents client-side issues, and 5xx indicates server-side errors. From an SEO perspective, codes such as 404, 410, 403, 429, 500, 502, 503, and 504 should be closely monitored. When search engine bots frequently encounter these codes, they may remove pages from the index, reduce crawl frequency, or interpret the site's quality signals negatively.

For example, if there are 12,000 404 errors in a log file with 100,000 lines, this situation may not just be a few broken links. An incorrect sitemap, outdated URL structures, broken internal links, improper canonical usage, removed media files, or bot attacks can all create the same scenario. Similarly, if 500 errors are concentrated at specific times, it may be necessary to examine PHP memory limits, database connection pools, disk I/O, or cache layers.

Brief Meanings of 4xx and 5xx Errors

Before writing a script, it is essential to understand what each code signifies. Otherwise, it is possible to misinterpret the resulting list. Not every 404 requires immediate action, and not every 403 indicates a security vulnerability; however, recurring errors that receive user or bot traffic should be prioritized.

Brief Meanings of 4xx and 5xx Errors
CodeTypeMeaningTypical Action
4004xxBad request or malformed parameterCheck application and redirect rules
4034xxAccess forbiddenReview permissions and security rules
4044xxResource not foundFix the broken link or add a 301 redirect
4104xxResource permanently removedIf intentional, clean sitemap and internal links
4294xxToo many requestsCheck rate limits, bot traffic, and CDN settings
5005xxGeneral server errorCheck application logs, PHP, and database errors
5025xxBad GatewayCheck proxy, upstream service, or PHP-FPM connections
5035xxService unavailableExamine resource usage, maintenance mode, and limits
5045xxGateway timeoutAnalyze slow queries, timeout values, and network latency

Do Not Write a Script Without Understanding the Log Format

Apache and Nginx typically produce similar access log formats. The most common line structure is: IP address, timestamp, request method and URL, HTTP version, status code, response size, referer, and user-agent. For the script to work correctly, it is crucial to know the field where the status code is located. Although the status code usually appears as the ninth field in Apache's combined log format, the request part in quotes contains spaces, which can mislead simple field counting.

Therefore, a robust extraction method should capture the HTTP request part of the line followed by the three-digit status code using regular expressions. If the Nginx log format has been customized, for example by adding additional fields such as upstream_response_time or request_time, the script's regex rule should be tested accordingly. As a first step, performing manual verification on a 20-line sample log is a good practice.

For practical checks, the following approach can be adopted in the terminal: first, view the last lines of the log file, then deliberately call a URL that generates a 404 and check how it is written in the access log. This small test prevents you from generating reports based on incorrect columns for hours.

How Does the URL Extraction Script for 4xx and 5xx Errors Work?

A good URL extraction script for 4xx and 5xx errors should not only find the error lines but also group the errors to report the count, last seen date, status code, and URL path. A 404 that has been seen once is not equivalent to a 404 that has been seen 20,000 times. Additionally, since 5xx errors are generally more critical, it is recommended to report them in a separate file.

The basic workflow is as follows:

  • Read the log file line by line.
  • Filter lines with HTTP status codes between 400 and 599.
  • Extract the URL path, method, and status code.
  • Count the combinations of the same status code and URL.
  • Sort the most frequently occurring errors to show them above.
  • Optionally, save the user-agent field separately to differentiate between bots and real users.
  • Create a CSV output to make it shareable within the team.

In a Linux environment, small sites may be adequately served by awk, grep, sort, and uniq commands. For larger sites, Python offers more flexible results with reading, memory management, support for compressed files, and date range filtering. If your log file is several GBs in size, it is necessary to process it line by line instead of loading the entire file into memory.

Quick Solution: Single-Line Command Logic

The fastest method for testing is to extract lines with 4xx and 5xx codes from the access log file and count them based on URLs. In a simple Apache/Nginx combined format, the following logic can be used: the awk command searches for requests starting with methods like GET, POST, HEAD; if the following HTTP status code starts with 4 or 5, it counts the URL path. The output is then sorted from the highest count to the lowest using sort.

The conceptual logic of the example single-line command is: read the log file, filter for status codes 4xx or 5xx, extract method and URL fields, group the same records, and show the top 50 results. This method is sufficient for a quick log check; however, if you require separation by date, user-agent, referer, or domain, a full script would be more accurate.

If you are using shared hosting, you can download the log file to your computer and run the same commands in the macOS or Linux terminal. Windows users can perform similar analyses on WSL, Git Bash, or PowerShell. If your site is on WordPress, some of the 404s in the log may be due to deleted media files, old plugin paths, or bot attempts from wp-admin. For WordPress performance and security, WordPress hosting solutions and SSL Certificate Installation resources can be beneficial.

Sample Bash Script Design

The following script approach provides a practical start in a production environment. The script reads the provided access log file, captures 4xx and 5xx status codes, counts URLs based on the status code, and reports in CSV format. Before running the script, you should adjust the log path and output file name according to your environment.

The simplified flow of the script is as follows: assign the access.log path to the LOG_FILE variable; assign the report file name to the OUTPUT variable; use awk to capture the HTTP request and status code from the line; if the code is between 400 and 599, create a status,url key; in the END section, print the total count for each key; sort in descending order by count; and complete the CSV report by adding a header row.

The command example conceptually is: ./find-http-errors.sh /var/log/nginx/access.log error-url-report.csv. At the end of the run, the CSV will contain status, url, and count columns. For instance, you might see records like 404,/old-product.html,184 or 500,/checkout,37. This report facilitates communication among SEO experts, developers, and system administrators regarding the same data.

Three additional enhancements are recommended to make the script more robust. First, support for compressed access.log.1.gz files with zcat or zgrep. Second, adding a date range filter to analyze only the last 24 hours or a specific campaign period. Third, including referer and user-agent fields to identify the source of the error. Particularly, 404 and 5xx errors caused by Googlebot can be critical from a technical SEO priority perspective.

More Flexible Log Extraction with Python

For large projects, Python provides a more readable and extensible option compared to bash commands. A Python script can capture the method, URL, HTTP version, and status code using regular expressions; then count the status and URL pairs with collections.Counter. It can also open compressed logs with the gzip module, write reports with the csv module, and accept command-line parameters with argparse.

For example, parameters usable in a Python script could include: --log access.log, --output errors.csv, --min-status 400, --max-status 599, --top 1000. This way, the same script can report all errors, only 5xx errors, or the top 100 most frequently occurring URLs. You can use cron to regularly generate the report. For instance, the script can run every night at 03:30, analyze the logs from the previous day, and write the report to the /var/reports/http-errors directory.

Another advantage of the Python approach is the ability to rank errors by importance score. A simple scoring formula could be: occurrence count x code weight x bot weight. By assigning a weight of 3 to 5xx errors, 1 to 404 errors, and 2 for lines containing Googlebot user-agent, more critical errors rise to the top of the list. This kind of prioritization makes managing hundreds of thousands of faulty records feasible for large e-commerce sites.

Interpreting the Output: Which Errors Should Be Fixed First?

Interpreting the Output: Which Errors Should Be Fixed First?

After receiving the report, the actual value lies in interpreting the data correctly. A common mistake is to automatically add 301 redirects to every URL appearing first on the list. While this approach may seem to reduce the number of 404s in the short term, irrelevant redirects can degrade user experience and search engine signals. If a product has been removed and no equivalent product exists, a 410 or a meaningful category page may be more appropriate.

For prioritization, the following order can be used:

  • 5xx errors: These should be urgently examined, especially on critical URLs like checkout, login, cart, API, and homepage.
  • 4xx errors crawled by Googlebot: They could stem from sitemap, internal links, or canonical issues.
  • High-traffic 404s: These directly affect user experience and require appropriate redirects or content recovery.
  • Static file errors: Missing CSS, JS, and image files can impact page appearance and Core Web Vitals metrics.
  • Irrelevant bot scans: While they should be monitored for security and rate limits, they may have lower SEO priority.

For example, if the URL /campaign-2024 returns a 404 eight thousand times a month and still receives backlinks, it makes sense to redirect it to the relevant new campaign page or the closest category with a 301. Conversely, paths like /phpmyadmin or /wp-login.php that are not present on your site and are being tried by bots should not be seen as an SEO issue; here, firewall, WAF, and rate limiting are more critical. For secure connections and user trust, you may want to evaluate Hostragons SSL Certificates.

Key Differences to Consider for Apache and Nginx

While Apache and Nginx access logs may look similar, differences can arise when using reverse proxies, CDNs, load balancers, or custom log formats. If Nginx is behind PHP-FPM, 502 and 504 errors may accumulate on the upstream side. If Apache uses mod_proxy, the error may root in the backend application. Therefore, both access logs and error logs should be examined together.

In Apache, for 500 errors, the error.log file may show PHP fatal errors, .htaccess typos, or permission issues. In Nginx, you should look for terms like upstream timed out, connect failed, or permission denied in error.log. If your site experiences high traffic, not only application fixes may be necessary, but server resources may need to be upgraded as well. For projects experiencing traffic spikes, Hostragons Cloud Server or High-performance hosting options may provide more stable results.

SEO Implications of Analyzing 4xx and 5xx Logs

In 2026, SEO standards dictate that technical health is not limited to on-page optimization. Search engines expect a site to produce fast, accessible, consistent, and reliable responses. Log analysis allows you to catch issues that may not be visible in Google Search Console or that appear with delays in near real-time. Regular log analysis is essential, especially for large sites, to prevent waste of crawl budget.

When conducting log analysis, the following questions should be answered: Which 404 URLs is Googlebot crawling? Are there URLs returning 404 or 5xx in the sitemap? Are mobile bots receiving different responses than desktop bots? Are there paths that fall to 404 at the end of 301 chains? Is there an increase in 503 errors during peak hours? When you find answers to these questions, you not only correct errors but also ensure that search engines can crawl your site more efficiently.

In a hypothetical scenario, let’s assume an e-commerce site’s logs show 32,000 404 errors within a week. Analysis may reveal that 60% of these come from outdated filter parameters, 25% from deleted products, 10% from missing images, and 5% from bot scans. In this case, robots.txt, canonical, sitemap, 301 redirects, and product lifecycle policies should be addressed collectively. To maintain domain and brand authority, the Domain Lookup and Domain Record page is also a good starting point for new projects.

Automation: Regularly Running Reports with Cron

Log analysis is beneficial when performed once; however, when done regularly, it turns into an early warning system. Daily reports are recommended for production sites, and hourly reports for high-traffic sites. You can run the script at regular intervals with cron and send reports via email or Slack integration. It is also a good practice to define critical threshold values.

For example, the following thresholds can be used as a starting point: if the number of 500 errors exceeds 20 in the last hour, generate an alert; if the number of 404s exceeds 5% of the total requests daily, add it to the SEO checklist; if 5xx errors are seen on checkout or login URLs, send an urgent alert; if there is a 5xx record containing a Googlebot user-agent, notify the team channel. This approach allows you to catch errors before user complaints arise.

When storing reports, you should also consider the personal data and security aspects. IP addresses and user-agent information may be considered personal data in some cases. If you don't need to analyze, you can anonymize IPs or only retain URL, status, and count information in the reports. Also, ensure that log files are not publicly accessible on the web directory.

Common Mistakes and Best Practices

One common mistake when performing log analysis is automatically redirecting all 404s to the homepage. This can create soft 404 signals in the eyes of search engines. A second mistake is not grouping parameterized URLs as the same page. For instance, /product?id=10 and /product?id=11 may represent different issues; however, tracking parameters like utm_source can unnecessarily bloat the report. A third mistake is losing the real client IP behind a CDN or load balancer. If X-Forwarded-For headers are not processed correctly, distinguishing between bots and users becomes challenging.

As a best practice, it is recommended to include at least the following fields in the report: status code, URL path, occurrence count, first seen, last seen, user-agent group, and referer. For small sites, status-url-count may suffice; however, as scale increases, resource analysis becomes crucial. Additionally, for 5xx errors, access log data should be correlated with application logs, database logs, and server resource usage graphs.

Another important point is to separate staging or test environment traffic from production reports. Test bots, uptime monitoring services, or security scanners can skew the report. Applying a user-agent whitelist and blacklist logic can clean the analysis output for more accurate results. If multiple domains are hosted on the same server, log separation by virtual host should be implemented, or the host field should be added to the report.

Quick Checklist

  • Verify that the log file belongs to the correct domain and date range.
  • View 4xx and 5xx codes in the same report, but prioritize 5xx errors separately.
  • Sort the most frequently occurring URLs in the top 50 or top 100.
  • Label user-agent records for Googlebot, Bingbot, and real users separately.
  • Check internal links, sitemap, and backlink sources for 404s first.
  • For 500, 502, 503, and 504, examine error logs, PHP-FPM, database, and resource usage together.
  • Assess the relevance of the target page before making automatic 301 redirects.
  • Regularly generate the report with cron and establish alert mechanisms for critical thresholds.

Conclusion

The script for extracting 4xx and 5xx error URLs from server access logs is a simple yet powerful tool that produces quick value in technical SEO, performance, and security audits. By correctly defining the log format and regularly reporting URLs, status codes, and occurrence counts, you can catch broken links, server errors, and wasted crawl budgets by bots earlier.

Bash commands may suffice for small sites; however, for larger, high-traffic projects, a Python-based system that runs with cron and generates alerts is more sustainable. Regularly monitoring your infrastructure, choosing the right hosting source, and implementing essential security layers like SSL will reduce error rates. If you are planning for a more stable web infrastructure, consider calmly evaluating Hostragons' hosting, VPS, domain, and SSL solutions according to your needs.

Frequently Asked Questions

Why should I analyze 4xx and 5xx errors separately in the access log file?

4xx errors typically indicate client-side issues like missing pages, permission problems, or bad requests, while 5xx errors show server, application, or infrastructure problems. Since 5xx errors directly impact accessibility, they generally require more urgent intervention.

Is a 404 error always an SEO problem?

No. Some 404s that are intentionally removed, do not receive traffic, and have no internal links are normal. However, 404 URLs present in the sitemap, with backlinks, or that receive user traffic should be corrected from an SEO perspective.

Can this script be used on shared hosting?

Yes. If you do not have terminal access on the server, you can download the access log file from the control panel and analyze it on your computer using Linux, macOS, WSL, or Git Bash. The important part is to read the log format correctly and interpret the report accurately.

Where should I first look for 5xx errors?

Start by identifying which URLs and times the error is concentrated in the access log. Then examine the web server error log, PHP-FPM or application logs, database connections, memory usage, CPU load, and disk I/O values together.

How often should I conduct log analysis?

For small sites, weekly or daily analysis may be sufficient. In e-commerce, news, SaaS, or high-traffic projects, hourly reporting and an automated alert system for critical 5xx thresholds are recommended.

Share this article:

Hostragons Team

Up-to-date guides from our expert team on hosting, servers, and domain names. Let's find the right solution for your project together.

Contact Us