Redirect to the maintenance page using .htaccess

From time to time, the website needs to be in maintenance mode to perform some actions (with the database and with code). In such cases, I use a simple redirect in the .htaccess file:

RewriteCond %{REQUEST_URI} !maintenance\.htm$
RewriteRule ^(.*)$ /maintenance.htm [L]

The above rules redirect all traffic to the maintenance page, a file of ‘maintenance.htm’ located in the root folder of my website. If there is a need for me still to have access to the site from my IP, I add one more line, so the whole redirect looks like this:

RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123$
RewriteCond %{REQUEST_URI} !maintenance\.htm$
RewriteRule ^(.*)$ /maintenance.htm [L]

In the example above, I placed the sample IP of 123.123.123.123 – please note that dots are escaped. This is why they are written as \.

My minimalistic ‘maintenance.htm’ file looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>The site is under maintenance</title>
    <style type="text/css">
        * { font-family: Helvetica, Arial, sans-serif; }
    </style>
</head>
<body>
    <h1>We&rsquo;ll be back soon!</h1>
    <div>
        <p>Sorry for the inconvenience but we&rsquo;re performing some maintenance at the moment. <br />
            If you need to you can always <a href="mailto:[email protected]">contact us</a>, otherwise we&rsquo;ll be
            back online shortly!</p>
        <p>&mdash; Yoursite Team</p>
    </div>
</body>
</html>

That’s all. In a few simple steps, you can limit access to your website during maintenance.