DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 9.2 Changing the Response Status for CGI Scripts

Problem

There may be times when you want to change the status for a response—for example, you want 404 Not Found errors to be sent back to the client as 403 Forbidden instead.

Solution

Point your ErrorDocument to a CGI script instead of a static file. The CGI specification permits scripts to specify the response status code.

In addition to the other header fields the script emits, like the Content-type: field, include one named Status: with the value and text of the status you want to return:

#! /bin/perl -w
print "Content-type: text/html;charset=iso-8859-1\r\n";
print "Status: 403 Access denied\r\n";
    :

Discussion

If Apache encounters an error processing a document, such as not being able to locate a file, by default it will return a canned error response to the client. You can customize this error response with the ErrorDocument directive, and Apache will generally maintain the error status when it sends your custom error text to the client.

However, if you want to change the status to something else, such as hiding the fact that a file doesn't exist by returning a Forbidden status, you need to tell Apache about the change.

This requires that the ErrorDocument be a dynamic page, such as a CGI script. The CGI specification provides a very simple means of specifying the status code for a response: the Status: CGI header field. The Solution shows how it can be used.

See Also

    [ Team LiB ] Previous Section Next Section