The following article explains, how to use the htaccess file in order to put a site or a part of the site in maintenance mode. I use to find myself in the position, where I need to put a site, or a part of a site, in maintenance mode to do changes on a productive server. This usually requires to block the whole site or certain parts and allow only my IP address, or several IP address of people working on the server to be allowed. On the one hand, this could be achieved via the Apache (v)host configuration. It is also possible to do it via the htaccess file, most of the times access is given. Furthermore, changing the htaccess file doesn’t require a restart of the web server afterwards.
If I want to block access to the whole site, I usually use the following htaccess configuration:
RewriteEngine on RewriteCond %{REQUEST_URI} !/maintenance.php RewriteCond %{REMOTE_ADDR} !=111.111.111.111 RewriteRule ^.*$ /maintenance.php [R=302,L]
The rules are rather easy: The first RewriteCond checks, if something else than maintenance.php is requested. The second RewriteCond checks, if the IP address is anything else than 111.111.111.111 (my IP address, but changed). So: If the user is not me and requested something else than maintenance.php, he will be redirected to maintenance.php. There I usually output a message, that the site is currently under maintenance.
If just a certain part of the site needs to be blocked, for example “/forum”, the first RewriteCond of the htaccess file can be changed accordingly:
Options +FollowSymlinks RewriteEngine on RewriteCond %{REQUEST_URI} /forum RewriteCond %{REMOTE_ADDR} !=111.111.111.111 RewriteRule ^.*$ /maintenance.php [R=302,L]
This will block the /forum and any subfolder for every IP except 111.111.111.111. I recommend using R=302 (temporarily moved) instead of R=301 (permanent) redirect, because browsers tend to cache rewrite rules which are defined as R=301. This may cause persistent redirects to maintenance.php, also if the maintenance work is finished and the rules are removed/commented again.
It is also possible to include several IP addresses:
RewriteEngine on RewriteCond %{REQUEST_URI} !/maintenance.php RewriteCond %{REMOTE_ADDR} !=111.111.111.111 RewriteCond %{REMOTE_ADDR} !=222.222.222.222 RewriteCond %{REMOTE_ADDR} !=333.333.333.333 RewriteRule ^.*$ /maintenance.php [R=302,L]
More information about htaccess and mod-rewrite can be found on the Apache homepage.