Paulund

Use htaccess To Redirect Custom Error Pages

When your website server sends a HTTP error status code it will display some default pages which do not look good on your site and don't look professional. The best solution to use if your server returns with an error is to display a custom error page with your own website skin. There are different ways you can make the server display your custom error pages. You can either use your server side language to search for HTTP error codes before displaying a page and redirect the visitor to a custom page for that error. An easier option is to use your htaccess file to redirect the visitor when it detects a server error code. Use the following htaccess snippet to redirect visitors to custom error pages.


ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
ErrorDocument 502 /502.html
ErrorDocument 504 /504.html

Display Error Pages With PHP

If you don't want to create 7 different pages for your error codes and would like to use the same page but change the text depending on what the error code is then the best option is to use PHP to change the content. First we use htaccess to redirect all codes to the same page.


ErrorDocument 400 /error-code.php
ErrorDocument 401 /error-code.php
ErrorDocument 403 /error-code.php
ErrorDocument 404 /error-code.php
ErrorDocument 500 /error-code.php
ErrorDocument 502 /error-code.php
ErrorDocument 504 /error-code.php

Now you can just create one page error-code.php and add the following code to display different messages depending on the error code. Use the following code snippet to use a different title and description for the different error codes.


<?php

switch($_SERVER["REDIRECT_STATUS"]){
	case 400:
		$title = "400 Bad Request";
		$description = "The request can not be processed due to bad syntax";
	break;

	case 401:
		$title = "401 Unauthorized";
		$description = "The request has failed authentication";
	break;

	case 403:
		$title = "403 Forbidden";
		$description = "The server refuses to response to the request";
	break;

	case 404:
		$title = "404 Not Found";
		$description = "The resource requested can not be found.";
	break;

	case 500:
		$title = "500 Internal Server Error";
		$description = "There was an error which doesn't fit any other error message";
	break;

	case 502:
		$title = "502 Bad Gateway";
		$description = "The server was acting as a proxy and received a bad request.";
	break;

	case 504:
		$title = "504 Gateway Timeout";
		$description = "The server was acting as a proxy and the request timed out.";
	break;
}
?>

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring