Skip to main content

Configuring Error Handling

1. Understanding HTTP Error Codes

Code Meaning Description Common Use Case
400 Bad Request The server cannot process the request due to client error. Invalid syntax in request
401 Unauthorized Authentication is required but has failed or has not been provided. Accessing protected resource without login
403 Forbidden The server understands the request but refuses to authorize it. Insufficient permissions for resource
404 Not Found The requested resource could not be found on the server. Accessing non-existent page or file
500 Internal Server Error The server encountered an unexpected condition that prevented it from fulfilling the request. Server-side application error
502 Bad Gateway The server received an invalid response from an upstream server. Proxy or load balancer misconfiguration
503 Service Unavailable The server is temporarily unable to handle the request due to being overloaded or down for maintenance. Server under maintenance or overload

Example: Custom 404 Page Configuration

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ /404.html [NC,L]
</IfModule>

2. Configuring Custom Error Documents

Directive Description Values Notes
ErrorDocument Defines custom error documents for specific HTTP status codes or URLs 404, 500, 403, etc. Can point to a local file or URL

Example: Custom 404 Error Page

<Directory "/var/www/html">
    ErrorDocument 404 /errors/404.html
</Directory>

Example: Custom 500 Error Page with URL

ErrorDocument 500 https://example.com/error.html
Note: The ErrorDocument directive can be used at the server, virtual host, or directory level.

3. Creating Custom Error Pages

Directive Description Example
ErrorDocument Specifies the document to be sent to the client when an error occurs. ErrorDocument 404 /errors/404.html
ErrorDocument Can also be used with a URL to redirect to an external page. ErrorDocument 500 https://example.com/error.html

Example: Custom 404 Page

<html>
<head><title>Page Not Found</title></head>
<body>
  <h1>404 - Page Not Found</h1>
  <p>The page you requested could not be found.</p>
</body>
</html>

Example: Using ErrorDocument with a Script

## In .htaccess or httpd.conf
ErrorDocument 403 /scripts/error_handler.cgi?code=403
Note: The ErrorDocument directive can be used for any HTTP status code, including 400, 401, 403, 404, 500, and others.

4. Using Server-Side Includes in Error Pages

Server-Side Includes (SSIs) can be used within error pages to dynamically generate content based on server variables or conditions. This allows for more flexible and context-aware error handling.

Directive Description Default Notes
SSI Enables or disables Server-Side Includes for a directory or file Off Must be set to On to enable SSI processing in error pages
Includes Enables or disables the inclusion of files via SSI directives Off Required for <!--#include--> to work

Example: Basic SSI in Error Page

<!--#echo var="date_gmt" -->
<p>An error occurred on <!--#echo var="date_gmt" --></p>
<!--#if expr="${REQUEST_URI} =~ /admin/" -->
<p>Please contact the administrator.</p>
<!--#else -->
<p>Please try again later.</p>
<!--#endif -->
Note: SSI directives are processed before the error page is sent to the client, so they can include dynamic content like timestamps or conditional messages.
Warning: Be cautious when using SSI in error pages as it may expose sensitive server information or lead to performance issues if not properly configured.

5. Redirecting Error Pages to URLs

Directive Description Values Notes
Redirect Redirects requests to a new URL 301, 302, 303, 307, 308 Used for error page redirections
RedirectMatch Redirects based on regex pattern matching 301, 302, 303, 307, 308 Allows pattern-based redirects for error pages

Example: Redirecting 404 to a custom page

Redirect 404 /custom-404.html

Example: Redirecting 500 errors to an external URL

Redirect 500 https://example.com/error-500.html

6. Handling Missing Files

Directive Description Default Notes
ErrorDocument Specifies the document to serve when a specific error occurs, including 404 (not found) errors. None Can be used to display custom error pages for missing files.

Example: Custom 404 Page

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /404.html [R=404,L]
</IfModule>

Example: Using ErrorDocument for 404

ErrorDocument 404 /errors/404.html
Note: The ErrorDocument directive can be used to provide a custom page for missing files or other HTTP errors.

7. Managing Server Errors

Error Code Description Default Handler Notes
400 Bad Request ErrorDocument 400 /errors/bad-request.html Client sent malformed request
401 Unauthorized ErrorDocument 401 /errors/unauthorized.html Authentication required but failed
403 Forbidden ErrorDocument 403 /errors/forbidden.html Access denied to resource
404 Not Found ErrorDocument 404 /errors/not-found.html Requested resource does not exist
500 Internal Server Error ErrorDocument 500 /errors/internal-error.html Server encountered an error
503 Service Unavailable ErrorDocument 503 /errors/service-unavailable.html Server temporarily unable to handle request

Example: Custom 404 Error Page

<html>
<head><title>Page Not Found</title></head>
<body>
  <h1>404 - Page Not Found</h1>
  <p>The requested page could not be found.</p>
</body>
</html>

Example: Configuring Error Documents

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ /errors/not-found.html [L]
</IfModule>

ErrorDocument 404 /errors/not-found.html
ErrorDocument 500 /errors/internal-error.html
Note: Error documents can be static HTML files or dynamic scripts, as long as they are accessible by the web server.
Warning: Avoid using ErrorDocument directives inside <Directory> or <Location> blocks unless necessary to prevent conflicts.

8. Setting Up Maintenance Mode

Directive Values Description
ErrorDocument 503 Specifies the error document for 503 Service Unavailable errors
ErrorDocument 503 /maintenance.html Points to a custom maintenance page for 503 errors

Example: Maintenance Mode Configuration

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_URI} !/maintenance.html$
  RewriteRule ^.*$ /maintenance.html [R=503,L]
</IfModule>

ErrorDocument 503 /maintenance.html
Note: The ErrorDocument 503 directive is used to display a custom page when the server is in maintenance mode.
Warning: Ensure that the maintenance page is accessible and does not contain sensitive information.

9. Using Graceful Error Degradation

Graceful error degradation ensures that when an error occurs, the server can continue to serve content or provide a fallback response rather than failing completely. This is particularly important for maintaining availability and user experience in production environments.

Error Type Description Configuration Directive Default Behavior
500 Internal Server Error Server encountered an unexpected condition that prevented it from fulfilling the request. ErrorDocument 500 /error/500.html Displays default Apache error page
404 Not Found Requested resource was not found on the server. ErrorDocument 404 /error/404.html Displays default Apache error page
403 Forbidden Server understood the request but refuses to authorize it. ErrorDocument 403 /error/403.html Displays default Apache error page

Example: Custom Error Pages

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /error/404.html [R,L]
</IfModule>

ErrorDocument 500 /error/500.html
ErrorDocument 404 /error/404.html
ErrorDocument 403 /error/403.html
Note: Ensure that custom error pages are accessible and do not trigger additional errors. Use absolute paths or ensure the server can resolve relative paths correctly.

Best Practices for Error Degradation

  • Provide user-friendly error pages with clear instructions or links to help.
  • Log errors for debugging and monitoring purposes.
  • Use static content for error pages to avoid recursive failures.

10. Configuring Default Error Responses

Directive Description Default Notes
ErrorDocument Specifies the document to be sent to the client when an error occurs. None Can be used for custom error pages or messages.

Example: Custom 404 Page

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ /404.html [L]
</IfModule>

Example: Default 500 Error Page

ErrorDocument 500 "<h1>Internal Server Error</h1><p>Something went wrong.</p>"

11. Testing Error Responses

Example: Simulate 404 Error

curl -I http://localhost/nonexistent-page.html
Error Code Description Test Command Expected Response
404 Page not found curl -I http://localhost/missing.html Status: 404 Not Found
500 Internal server error curl -I http://localhost/error-page Status: 500 Internal Server Error
Note: Use curl -I to fetch only headers for testing error pages without content.

12. Analyzing Error Patterns in Logs

Log Level Description Typical Use Case Example Message
error Errors that prevent a feature from functioning properly Debugging failed requests or module issues [error] [core:alert] [pid 12345] mod_rewrite.c(123): RewriteEngine not found
warn Warnings that indicate potential problems but do not stop processing Monitoring for deprecated features or misconfigurations [warn] [core:warn] [pid 12345] RewriteMap not defined
info Informational messages about server activity General monitoring and operational awareness [info] [core:info] [pid 12345] Apache/2.4.57 (Unix) configured
debug Detailed debugging information useful for developers Diagnosing complex issues or performance bottlenecks [debug] [core:debug] [pid 12345] mod_rewrite.c(123): RewriteRule matched

Example: Log Analysis Script

#!/bin/bash
# Analyze Apache error logs for common patterns
grep -E "(\[error\]|\[warn\])" /var/log/apache2/error.log | \
  awk '{print $4 " - " $5}' | \
  sort | uniq -c | sort -nr
Note: The ErrorLog directive controls where error messages are logged. By default, logs go to the system's syslog or stderr.

Common Error Log Patterns

  • Permission Denied - Usually related to file permissions or directory access.
  • Module Not Found - Indicates missing or misconfigured modules.
  • Syntax Errors - Found in configuration files like .htaccess or httpd.conf.
  • Timeouts - May indicate server overload or misconfigured proxy settings.

Was this article helpful?