Primary image for Pro Tip: Redirecting to a Custom Nginx Maintenance Page

Pro Tip: Redirecting to a Custom Nginx Maintenance Page

Here’s one I struggled with a bit while upgrading lincolnloop.com yesterday.

Scenario: You need to take your site offline and want to redirect all its traffic to a “down for maintenance” page. For search engine friendliness, that page should return a 503: Service Unavailable status code. Here’s the (not entirely intuitive) way to do that in Nginx:

server {
        listen      80;
        server_name mysite.com;
        root    /var/www/mysite.com/;

        location / {
            if (-f $document_root/maintenance.html) {
                return 503;
           }
             # the rest of your config goes here
         }

        error_page 503 maintenance</span><span class="p">;</span><span class="w"></span>
<span class="w">        </span><span class="kn">location</span><span class="w"> </span><span class="s">maintenance {
                rewrite ^(.*)$ /maintenance.html break;
        }
}
Now whenever you need to take your site offline, simply create the file maintenance.html in the $document_root (in our case, /var/www/mysite.com). If the file exists, Nginx will serve it with a 503 status code, if not, it will proceed as usual.
Peter Baumgartner

About the author

Peter Baumgartner

Peter is the founder of Lincoln Loop, having built it up from a small freelance operation in 2007 to what it is today. He is constantly learning and is well-versed in many technical disciplines including devops, …