How to configure Nginx so you can quickly put your website into maintenance mode
I had to rebuild my Rackspace VPS last night where my Django app runs as I wanted to downgrade it because it was underutilized. Since I was already at the lowest tier for that category of servers, there's no option to resize it down, I would need to spin up a new server from a different server category.
Thanks to Ansible, though, provisioning a new server with all the applications and configurations I needed only took about 5 minutes. But because of the new public IP that was assigned to this server, I had to change the A record for my domain which could take hours to fully propagate across DNS servers around the world.
I configured Nginx on my old server to display an “Under Maintenance" page while I wait for the DNS change to take effect. I figured this is something that would be really nice to be able to turn on and off quickly so I looked for a solution to do so.
Here's the solution I found (my configuration is a little bit different from the original source):
1. Create a custom maintenance page and call it maintenance_off.html
I forgot where I got this example from, but here's what I use:
<!DOCTYPE html> <title>Site Maintenance</title> <style> body { text-align: center; padding: 150px; } h1 { font-size: 50px; } body { font: 20px Helvetica, sans-serif; color: #333; } article { display: block; text-align: left; width: 650px; margin: 0 auto; } a { color: #dc8100; text-decoration: none; } a:hover { color: #333; text-decoration: none; } </style> <article> <h1>We’ll be back soon!</h1> <div> <p>Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always <a href="mailto:support@glucosetrac ker.net">contact us</a>, otherwise we’ll be back online shortly!</p> <p>— The GlucoseTracker Team</p> </div> </article>
2. Change your app's Nginx configuration to check if the maintenance page exists
server { ... location / { if (-f /webapps/glucosetracker/maintenance_on.html) { return 503; } ... } # Error pages. error_page 503 /maintenance_on.html; location = /maintenance_on.html { root /webapps/glucosetracker/; } ... }
What the configuration above will do is to check whether a file called maintenance_on.html exists in the specified path and if true, Nginx will return a 503 error.
Then at the bottom, we're telling Nginx that for 503 errors, serve the page /maintenance_on.html, which is located in /webapps/glucosetracker/ directory.
3. Whenever you want to bring your website into maintenance, simply rename maintenance_off.html to maintenance_on.html
Nginx will automatically return the a 503 error and serve that page. Rename it back to maintenance_off.html when you're finished. No restarts necessary.