Quick and Clean Maintenance Mode for your site

Read it later:

Some web frameworks and CMSs have a so-called “maintenance mode” feature. This allows you to work on your site freely (e.g. perform updates) while your users see a friendly maintenance page. This solution is usually good enough but what if you need to work on your code? Is there a way to let the web server manage the maintenance code directly? If you use Apache the answer is yes.

Your web server should support mod_rewrite and .htaccess files, which are two common features today. Let’s see the code first:

<IfModule mod_rewrite.c>
    RewriteEngine On

    ## Maintenance rewrite rule
    ## Create a .maintenance empty file in the Doc Root in order to activate
    ## Edit the REMOTE_ADDR condition IP
    ## Note: this doesn't work with reverse proxies
    RewriteCond %{DOCUMENT_ROOT}/.maintenance -f
    RewriteCond %{REMOTE_ADDR} !=[your IP here]
    RewriteRule ^(.*)$ maintenance.php [L]

    ## Main Site Rule
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]

The first condition checks for the existence of a file named .maintenance in the document root of your site. If the condition is met the next condition checks the IP address of the remote user, if the IP is different from the one of your choice, the maintenance.php file (or the file you want) is displayed. The remaining lines perform a standard redirect of all URLs to a front controller file, a very common practice to use friendly URLs within your site.

These settings can be always active in your .htaccess file. When you want to switch to maintenance mode all you have to do is create the empty .maintenance file with your favorite program or with terminal access:

ragman@myserver/var/www/$ touch ./.maintenance

And when you’re done delete the file and the site is back online.

The WordPress variant

WordPress uses a non-empty .maintenance file during platform updates. To avoid conflicts simply change the above code using another name for your trigger file, for example .offline.