Custom error pages with PHP-CGI

From DreamHost

Jump to: navigation, search

One of the potential frustrations you could encounter in running PHP-CGI (the DreamHost default configuration) is that Custom error pages will not work in the way you probably want them too unless you make some accommodation using .htaccess.

The following information on "workarounds" for this issue was adapted from posts left in the the "user comments" section of the old DreamHost Knowledge Base (KB) article.

Method 1

# in /home/user/yourdomain/.htaccess
ErrorDocument 404 /404.html
RewriteEngine on
Rewritecond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule \.php$ /404.html

Simply change either /404.html to anything you'd like, and change .php to whatever filetype you are using to serve php)

Method 2

This is a suggested patch/fix to Method 1 above. The following line:

Rewritecond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f

should be either:

RewriteCond %{SCRIPT_NAME} !-f

-or-

RewriteCond %{DOCUMENT_ROOT}%{SCRIPT_FILENAME} !-f

The reason for this change: The version in Method 1 tried to see if a file existed, like it should, but it did not properly account for parameters in the URL (i.e., file.php?arg=value). The following data shows a sample of how'd the values used above would look like (sample random data).

DOCUMENT_ROOT /home/user/webroot/
SCRIPT_NAME /home/user/webroot/folder/file.php
SCRIPT_FILENAME /folder/file.php
REQUEST_URI /folder/file.php?argument=value

Additionally, to the end of the rewrite rule, you might want to add "[QSA]" (without the quotes) to append the Query String (the ?argument=value part) to the rewritten URL. For a generic 404 error page, as the original was designed for, this would not be necessary.

So, to finish up, I provide you with an improved version

# Start 404 error page
<IfModule mod_rewrite.c>
RewriteEngine On
##this next part was included in Method 1
##it solves the "No input file specified" issue
##NEXT LINE COMMENTED. ALTERED VERSION FOLLOWS. DEALS WITH ANY QUERY STRING PROBLEMS
# RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f #this fails with any GET parameters
RewriteCond %{SCRIPT_NAME} !-f
RewriteRule (.+) /404.phpx?request=$1 [PT]
</IfModule>
#End

A comment regarding the two methods

The patch in Method 2 has been reported to not work correctly while, in fact, the one given in Method 1 reportedly works even with parameters in the url.

It is suggested to add another line to the .htaccess so that when the url is a directory, users are not directed to the error page but to an index.php file.

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule (.+) /404.html
Personal tools