Today I had to search quite a long time how to use Apache’s mod_rewrite to create a “maintenance” page for a web server. The goal was to:
- Redirect all URLs usually going to http://foo/go/bar to http://foo/maintenance-light.html
- Redirect all other URLs to http://foo/maintenance.html
All the maintenance pages are also using some CSS and images. Creating this redirection sounds really stupid and simple, but one thing wasn’t clear in the documentation and it took me quite a while to figure it out…every RewriteCond is only valid until the next RewriteRule! Not knowing that, I had infinite loops on the second RewriteRule…so I hope that this post will help someone else to avoid this problem.
The lines to add to your Apache config are:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/maintenance.html$
RewriteCond %{REQUEST_URI} !^/maintenance-light.html$
RewriteCond %{REQUEST_URI} !/img/(.*)$
RewriteCond %{REQUEST_URI} !/css/(.*)$
RewriteRule ^/go/ /maintenance-light.html [R,L]
RewriteCond %{REQUEST_URI} !^/maintenance.html$
RewriteCond %{REQUEST_URI} !^/maintenance-light.html$
RewriteCond %{REQUEST_URI} !/css/(.*)$
RewriteCond %{REQUEST_URI} !/img/(.*)$
RewriteRule $ /maintenance.html [R,L]
The first line is there to simply enable the Apache rewrite engine. Then we have 4 lines to “exclude” some paths from being rewritten and finally we find the rewrite rule. Note that they are processed in order. The “L” flag instructs Apache to skip all the following RewriteRule statements as soon as the one is matched.
You can also use a non-redirecting RewriteRule to skip those URLs instead of conditions. For example:
RewriteRule =/maintenance.html – [L]