How to Return 503 Status Code in Apache Without External Scripts for Maintenance Mode


1 views

When putting a website into maintenance mode, returning a proper 503 (Service Unavailable) status is crucial for SEO. Here's the cleanest Apache-only solution using mod_rewrite:


RewriteEngine On
RewriteCond %{ENV:MAINTENANCE_MODE} =1
RewriteRule ^ - [R=503,L]
ErrorDocument 503 /maintenance.html

Control the maintenance mode by setting an environment variable in your virtual host configuration:


<VirtualHost *:80>
    SetEnv MAINTENANCE_MODE 1
    # ... other configurations ...
</VirtualHost>

For cases where you need to maintain some access while blocking others:


RedirectMatch 503 ^/(?!admin/).*

Enhance your 503 response with SEO-friendly headers:


ErrorDocument 503 "<html><head><title>Maintenance</title></head><body>Down for maintenance</body></html>"
Header always set Retry-After "3600" env=MAINTENANCE_MODE

For temporary maintenance windows, add this to your .htaccess:


<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{TIME} >20240220120000
    RewriteCond %{TIME} <20240220140000
    RewriteRule ^ - [R=503,L]
</IfModule>

When you need to take a site offline for maintenance while remaining SEO-friendly, returning proper HTTP 503 (Service Unavailable) status is crucial. Apache provides several built-in ways to achieve this without relying on external scripts like PHP or CGI.

The cleanest method is configuring Apache's ErrorDocument directive in your virtual host or .htaccess file:


ErrorDocument 503 "Service Unavailable - Maintenance in Progress"

For a custom maintenance page:


ErrorDocument 503 /maintenance.html

For more control, combine with mod_rewrite:


RewriteEngine On
RewriteCond %{ENV:MAINTENANCE_MODE} on
RewriteRule ^ - [R=503,L]

For Apache 2.4 and later, you can use the Return directive:


Return 503 "Service Temporarily Unavailable"

Here's a full configuration example:


<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html
    
    ErrorDocument 503 /maintenance.html
    
    RewriteEngine On
    RewriteCond /var/www/maintenance.flag -f
    RewriteRule ^ - [R=503,L]
</VirtualHost>

After implementing, verify with curl:


curl -I http://example.com

You should see:


HTTP/1.1 503 Service Unavailable