Friday, January 4, 2013

Redirecting everything past root in apache


Ever needed to do some maintenance on an Apache web server? Well I do, and I had been wanting to redirect everyone to a maintenance webpage so that they would see that the temporary link instead of any of the actual website. 

I used to do this by putting in place a different configuration file for the Apache web server and allowing it to redirect to the maintenance page, with the following being the main line in the configuration file:

DocumentRoot /var/www/html/maintenance

This was a pain for two reasons:

  1. It meant that I had to go in and save the actual config file off to another temp file, then rename the maintenance config file to be the actual config file
  2. When anyone requested a webpage that wasn't the DocumentRoot of the website it would not get redirected to the maintenance page

So after some ooogooglygoogling I was able to find the following nugget:

RewriteEngine Off
RewriteCond   %{REQUESR_URI} !=/index.html
RewriteRule   ^ /var/www/html/maintenance/index.html

in the configuration file of the actual website Apache config. This means that I can keep the same configuration file for my maintenance and my actual site, doing away with any pesky moving and renaming etc. and switch between the maintenance and production with just putting the rewrite engine off or on.


It also means that anyone requesting a webpage that is not at the route of the website will be directed back up to the maintenance page. It does this by matching anything from the start of the line - denoted by the '^' i.e. the start of the line, and redirecting to the html file denoted in the second part of the RewriteRule directive.

This is much easier for me maintaining less files, and a more natural feel when people have to be redirected going to the site.