Custom Maintenance Page for nginx

Jan Dudulski

Custom Maintenance Page for nginx

From time to time you need to turn off your app to make some more complicated changes, fix the mess when something goes wrong etc. In short - you want to turn maintenance mode on. In this brief article I will show you the simplest solution for apps running on awesome nginx.

What do we need?

  1. An app with nice looking 503.html in public folder

  2. User with access to the server (we recommend to create one user per app)

  3. Nginx configured for serving your app

Here's the example of missing configuration with explanation below.

server {
  # ...
  # your config which handles the app
  # ...

  if (-f /home/user/maintenance) {
    return 503;
  }

  error_page 503 @maintenance;

  location @maintenance {
    if ($uri !~ ^/assets/) {
      rewrite ^(.*)$ /503.html break;
    }
  }
}

What is what

if (-f /home/user/maintenance) {
  return 503;
}

At the beginning we are checking for existence of maintenance file in the user $HOMEDIR. If it exists we are returning server HTTP 503 error code, which tells a browser (and also - more importantly - to the uncle google) that application is currently in maintenance mode.

error_page 503 @maintenance;

This directive will handle 503 error code with our @maintenace location definition. If you want you can pass just an uri.

location @maintenance {
  if ($uri !~ ^/assets/) {
    rewrite ^(.*)$ /503.html break;
  }
}

And the final named location. We redirect every request to our 503.html except paths starting with /assets/ (or another path where your assets are stored) since we need some stylesheets and images to make 503 more fancy than sad default:

Meet Ruby on Rails experts

We’ve been doing Ruby on Rails since 2010 and our services quality and technical expertise are confirmed by actual clients. Work with experts recognized as #1 Ruby on Rails company in the World in 2017 by Clutch.

Talk to our team and confidently build your next big thing.

Jan Dudulski avatar
Jan Dudulski