Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple HTML Maintenance Page for Apache using rewrite_module

Apache - Maintenance Page

  • Activate/Deactivate with a file.
  • Bypass with a custom request header.

With the following Apache Rewrite rule, temporarily redirect all traffic to a maintenance page when a file named maintenance exists at the same level as the DocumentRoot directory. i.e. if your DocumentRoot is /var/www/public_html/ then creating the file /var/www/maintenance would trigger Maintenance mode.

Use something like the ModHeader Chrome browser extension to bypass the maintenance page by setting a X-Maintenance request header with a value of tF0BOCn4z8HgG2Kw (replace this with your own unique passcode string).

Instructions

1 - Create a Maintenance Page

Add a maintenance page to your DocumentRoot - the page should be a self contained HTML document such as the following example.

<!DOCTYPE html>
<html>
    <head>
        <title>Maintenance</title>
        <style>
            body{color:#666;background-color:#f1f1f1;font-family:sans-serif;margin:12%;max-width:50%;}
            h1,h2{color:#333;font-size:4rem;font-weight:400;text-transform:uppercase;}
            h2{color:#333;font-size:2rem;}
            p{font-size:1.5rem;}
        </style>
    </head>
    <body>
        <h1>503</h1>
        <h2>Temporarily Offline</h2>
        <p>This site is currently closed for maintenance. Please check back again soon.</p>
    </body>
</html>

2 - Update your Apache configuration

Add the following rule to all required VirtualHost directives:

<LocationMatch "\.(css|gif|ico|jpe?g|js|png|svg)$">
    ErrorDocument 503 "Service unavailable."
</LocationMatch>
<IfModule mod_rewrite.c>
    <IfVersion < 2.4>
        ErrorDocument 503 /maintenance.html
    </IfVersion>
    <IfVersion >= 2.4>
        <If "! %{REQUEST_URI} =~ /\.(css|gif|ico|jpe?g|js|png|svg)$/i && -f '%{DOCUMENT_ROOT}/../maintenance'">
            ErrorDocument 503 /maintenance.html
        </If>
    </IfVersion>
    RewriteEngine On
    RewriteCond "%{HTTP:X-Maintenance}" "!^tF0BOCn4z8HgG2Kw$"
    RewriteCond "%{ENV:REDIRECT_STATUS}" !=503
    RewriteCond "%{DOCUMENT_ROOT}/../maintenance" -f
    RewriteRule ".*" "-" [R=503,L]
</IfModule>

3 - Restart Apache

Apply the configuration changes with a graceful restart

# apachectl graceful
@purdy

This comment has been minimized.

Copy link

@purdy purdy commented Oct 9, 2021

Wow, this is awesome! Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment