Recipe 9.1 Handling a Missing Host Field


You have multiple virtual hosts in your configuration, and at least one of them is name-based. For name-based virtual hosts to work properly, the client must send a valid Host field in the request header. This recipe describes how you can deal with situations in which the field is not included.


Add the following lines to your httpd.conf file:

Alias /NoHost.cgi /usr/local/apache/cgi-bin/NoHost.cgi RewriteEngine On RewriteCond "%{HTTP_HOST}" "^$" RewriteRule "(.*)" "/NoHost.cgi$1" [PT]

The file NoHost.cgi can contain something like the following:

#! /usr/bin/perl -Tw my $msg = "To properly direct your request, this server requires that\n"         . "your Web client include the HTTP 'Host' request header field.\n"         . "The request which caused this response did not include such\n"         . "a field, so we cannot determine the correct document for you.\n"; print "Status: 400 Bad Request\r\n\"     . "Content-type: text/plain\r\n\"     . 'Content-length: ' . length($msg) . "\r\n\"     . "\r\n\"     . $msg; exit(0);


Once the directives in the solution are in place, all requests made of the server that do not include a Host: field in the request header are redirected to the specified CGI script, which can take appropriate action.

The solution uses a CGI script so that the response text can be tailored according to the attributes of the request and the server's environment. For instance, the script might respond with a list of links to valid sites on the server, determined by the script at runtime by examining the server's own configuration files. If all you need is a "please try again, this time with a Host: field" sort of message, a static HTML file would suffice:

RewriteRule .* /nohost.html [PT]

A more advanced version of the script approach could possibly scan the httpd.conf file for ServerName directives, construct a list of possibilities from them, and present links in a 300 Multiple Choices response. Of course, there's an excellent chance they wouldn't work, because the client would still not be including the Host: field.

See Also


Apache Cookbook
Apache Cookbook: Solutions and Examples for Apache Administrators
ISBN: 0596529945
EAN: 2147483647
Year: 2006
Pages: 215

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: