There always come a time where you need to temporarily stop a site for some required maintenance. The simplest quick&dirty method would be to stop the web server, but it’s not pretty for the users and also it brings down all the sites you are hosting. Another method (which I’ve used in the past) was to disable the virtual host config for that specific site in Apache, the traffic will then fallback to another default virtual host that served only error pages – it worked, it was quick and selective (doesn’t affect all the hosted websites).
But it still wasn’t perfect, and some complications arose when I switched to using SSL/HTTPS and traffic would not fallback correctly to the default virtual host.
Here’s the current method I am using, it’s fast to activate when neeed (one-liner on the server) and easy to implement.
First, you’ll need a .htaccess in your document root and mod_rewrite activated in Apache. The .htaccess would contains something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# check if mod_rewrite is enabled <IfModule mod_rewrite.c> # activate mod_rewrite RewriteEngine On # check if a file exists called "maintenance-mode-on" in the document root RewriteCond %{DOCUMENT_ROOT}/maintenance-mode-on -f # safety check to prevent redirect loops RewriteCond %{REQUEST_URI} !/maintenance.php$ # redirect internally all requests to maintenance.php RewriteRule $ /maintenance.php [L] </IfModule> |
And then you’ll have a file called maintenance.php in the document root:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php // set the correct error http header, // mainly for search engines so they'll treat the page correctly and to not index it with the maintenance message header("HTTP/1.1 503 Service Temporarily Unavailable"); header("Status: 503 Service Temporarily Unavailable"); header("Retry-After: 3600"); // and add below whatever message you want ?> <html><body style="background-color:#fffbef; color: #e95d2a"> <br><br><br><br><br> <h2> <center> Temporarily unavailable due to scheduled maintenance. Please try again in a few minutes. <br> </center> </h2></body></html> |
You can activate maintenance mode by creating a file named “maintenance-mode-on” in the document root. It can be emtpy, it doesn’t matter.
You can then disable maintenance mode by deleting the file “maintenance-mode-on”.
Tip: I usually keep a text file called “maintenance-mode-off” in the document root with the above instructions so I’ll find it and know what to do.