Capistrao web enable and disable
Posted on January 6th, 2010Using a simple cap disable_web command allows my Rails apps to be completely disabled while I perform maintenance on the site without having to worry about users accessing it. Being able to suspend the site with a single command is cool…
First create a generic page that you want your users to see when your site is disabled and name it maintenance.html. Then throw it into your /config directory.
Cap Tasks
Next, write a disable_web task for Capistrano.
desc "This will disable the application and show a warning screen" task :disable_web do run "cp #{current_path}/config/maintenance.html #{current_path}/maintenance.html" end
This simple one liner will copy the maintenance.html file into the root of your application. Now lets write a task to re-enable the application.
desc "This will enable the application and remove the warning screen" task :enable_web do run "rm #{current_path}/maintenance.html" end
This will simply delete the maintenance file.
Ok, so, basically, when you run cap disable_web, Capistrano will move your maintenance file into the root of your app, and enable_web will delete it. So far this does nothing to disable your PHP application.
mod_rewrite Magic
The trick to this is using mod_rewrite to look for your maintenance file. If it’s at the root of your application, then all requests will be directed to it. Otherwise the application works as normal.
RewriteEngine On # Check for maintenance file and redirect all requests RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f RewriteCond %{SCRIPT_FILENAME} !maintenance.html RewriteRule ^.*(\.html|\.php)$ /maintenance.html [L]
This will look for any requests of .html and .php files. All requests that fit that condition will pointed to the maintenance.html page if it exists at the root of the application.