Sometimes it might be necessary to temporarily disable your website. This could be due to a pending update, a security issue that needs to be fixed or any other reason for which you don’t want any user to access the site.
There is an easy way to achieve this: Apache mod_rewrite – with which all requests can be redirected to a predefined page. With this method, maintenance mode can easily be enabled just by creating one file and disabled again by removing that file. The webserver does not need to be restarted.
1. Enable mod_rewrite
In your terminal type:
1 |
sudo a2enmod rewrite |
2. Edit Your Site
On Ubuntu, go to /etc/apache2/sites-enabled/ and edit the desired sites (i.e. 000-default and/or default-ssl). Add one of the following code blocks between the <VirtualHost></VirtualHost> tags.
a) Default Error Page
Use this code if the user should see Apache’s default error page:
Code:
1 2 3 4 5 6 7 |
# Maintenance Mode <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$ RewriteCond %{DOCUMENT_ROOT}/maintenance.enabled -f RewriteRule ^.*$ - [R=503,L] </IfModule> |
Explanation:
Line | Description |
2/7 | Execute the encapsulated code if mod_rewrite is enabled |
4 | The RewriteRule does not apply to the given IP address |
5 | The RewriteRule will only be executed if this file exists |
6 | The RewriteRule itself, which will take any input and result in a redirect ^ marks the beginning of a string . matches any single character * repeats the previous match zero or more times $ marks the end of a string [R=xxx] Redirect using the given status code [L] Last flag, do not process any further rules |
b) Custom Error Page
Use this code if you want the user to see a custom error page (i.e. maintenance.html):
Code:
1 2 3 4 5 6 7 8 9 10 |
# Maintenance Mode <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$ RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f RewriteCond %{DOCUMENT_ROOT}/maintenance.enabled -f RewriteCond %{SCRIPT_FILENAME} !maintenance.html RewriteRule ^.*$ /maintenance.html [R=503,L] ErrorDocument 503 /maintenance.html </IfModule> |
Explanation:
Line | Description |
7 | The RewriteRule does not apply to this file (since this is the custom error page that should be accessible) |
9 | Define a custom error page for status code 503 |
3. Usage
Now you can easily turn on and off maintenance mode by creating or deleting the file maintenance.enabled in your webroot. If using a custom error page, it should be placed in webroot as well.
Further information on mod_rewrite:
Leave a Comment