Disabling a Site for Essential Maintenance Using an Apache mod_rewrite Command

published 10.Mar.2006

The Problem

I had taken on some development work which required some extensive changes to an existing e-commerce site, all the database changes where tested on a development server, but to apply the upgrade I would need to take the live site off-line for a couple of hours to ensure no database changes where made by visitors during this time.

So I needed to find a way to effectively turn-off the whole site, and yet present the user with a polite message informing them of the upgrade, with details of when the site would be up and running. I decided to use Apaches mod_rewrite module to do the job, and created one rule which would redirect all traffic to a notice page. As the site had hundreds of pages indexed in the search engines, I didn't want to have to write many different rewrite rules.

The Solution, an Apache Mod_Rewrite Rule

An easy solution to the problem is to create an .htaccess in the root folder and add the following rules to the file, which turn on the mod_rewrite apache module, and redirects all traffic to a file called offline.php if the original request is not offline.php. So for example if the user requested index.html its not the file offline.php, so gets redirected to the offline.php file, hence the user gets the upgrade message.

The .htaccess rule :-

RewriteEngine on
RewriteRule !offline.php$ http://yoursite.com/offline.php [R,L]

The offline.php file is a simple PHP script which outputs a 503 HTTP header to indicate the service is currently unavailable; and outputs a suitable message for site visitors to let them know about the upgrade and maintenance work being undertaken. Outputting the 503 header is important just in case the search engine spider paid a visit during the upgrade. The spider should respect that the service is temporarily unavailable, and revisit at a later time.

<?php
header("HTTP/1.1 503 Service Unavailable");

echo 'Output suitable error message for site visitors';
?>

What Next?

Bookmark this article at :-

 

 

About Author:
I'm a father, husband, and a software developer who works for the NHS. more »

Sections :
« Articles
« Contact


 

FreeImage - an open source library project for developers who would like to support popular graphics image formats like PNG, BMP, JPEG, TIFF.