Graceful maintenance for Apache virtual hosts
May 16, 2009,
When disabling individual Apache virtual hosts for maintenance, it is desirable to send search engine friendly 503 headers for any domains configured in this virtual host. Fortunately, this takes very little work.
Occasionally you will have to take down an individual Apache virtual host to do some serious management. The problem with this is that visitors and perhaps even more important, search engine crawlers, will be faced with a site that is not in its final state, with all possible consequences. The proper way to handle this, is to return 503 (temporarily unavailable) headers. If you've read the article on log rotation, you already learnt how we send 503 headers when we do daily maintenance on our web servers. Sending these headers for selected virtual hosts proves to be even simpler.
First, we need a target page to which we redirect all traffic during maintenance. We use a simple PHP script that sends the header and a human readable message, and store this in /etc/httpd/alt-boot/503.php, but feel free to store this in any other location accessible to Apache.
<?php header("HTTP/1.0 503 Service Temporarily Unavailable"); echo "Temporarily down for maintenance"; ?>
We use PHP because it's very simple to send a header, and add code to do some other clever things with the request, but of course you can use any other language that allows you to set the response header.
Now, to disable a virtual host, you only need to add a single line at or near the top its configuration:
ScriptAlias / /etc/httpd/alt-boot/503.php/
Apache may warn you about aliases that are also in the configuration. You might want to outcomment these. The slightly awkward trailing slash of the target URL is necessary to divert all requested resources to the script.
Once you start sending 503 response headers, you may even remove the entire document root of the virtual host, and search engines and your visitors will be none the wiser.