Creating a Custom Maintenance Page for Nginx


Nathan Osman's Gravatar

Nathan Osman
published Aug. 6, 2014, 9:42 p.m.


If you've been following 2buntu for any length of time, you've probably noticed that our servers rarely go down. Our system administrators do an excellent job of staying on top of server issues, although they are quite rare.

Tools

Unfortunately, it is not always possible to avoid downtime. (At least, not with our budget or equipment.) Services need restarting, configuration files need updating, and sometimes the server itself needs to be restarted.

What We Do

In the event that we need to do something that affects the website, we display a custom maintenance page. It's not fancy or anything, but it gets the point across. You can view the contents of the file yourself by browsing the 2buntu source code. (Look in twobuntu/templates/maintenance.html.) Basically, this file is a self-contained static HTML file.

Naturally, we don't want search engines indexing the maintenance page if they happen to stumble across the site while the page is up. We avoid this problem by also returning an HTTP 503 (service temporarily unavailable) status code. Search engines recognize that this is an error page and will come back later when the site is back up.

Configuring Nginx

The next task is getting Nginx to display a single static page and return a 503 status code. We've created a configuration for 2buntu that looks something like this:

server {
    listen 80;
    server_name 2buntu.com www.2buntu.com;

    root <path>/twobuntu/templates;
    error_page 503 /maintenance.html;

    location /maintenance.html {
        # allow access to this specific page
    }
    location / {
        return 503;
    }
}

(Remember to replace <path> with the absolute path to your document root.) This configuration does the following:

  • specifies the document root where error templates lie
  • indicates that the maintenance.html page should be shown for 503 errors
  • allows access to the /maintenance.html path
  • raises a 503 error for all paths

Swapping It Out

We have developed a couple of scripts that let us easily swap out the maintenance page when we are actually performing maintenance.

start_maintenance

#!/bin/bash

ln -s /etc/nginx/sites-available/maintenance.conf /etc/nginx/sites-enabled/maintenance.conf
rm -f /etc/nginx/sites-enabled/<conf file>
service nginx restart

stop_maintenance

#!/bin/bash

ln -s /etc/nginx/sites-available/<conf file> /etc/nginx/sites-enabled/<conf file>
rm -f /etc/nginx/sites-enabled/maintenance.conf
service nginx restart

(Replace <conf file> with the name of your site's configuration file.) Once both of these scripts are created and marked executable, your workflow ends up looking something like this:

./start_maintenance
# ... do stuff ...
./stop_maintenance