配置Apache返回HTTP 503错误并启用CORS,兼容OPTIONS请求
Ah, I’ve run into this exact issue before! The problem here is that your browser’s preflight OPTIONS request isn’t getting the right combination of 503 status code and CORS headers from Apache. Browsers are strict about preflight responses—if they don’t see valid CORS headers alongside the status code, they block the request entirely, which is why you’re seeing that "invalid HTTP" error.
Let’s fix this step by step:
First, make sure Apache’s mod_headers module is enabled. On Debian/Ubuntu systems, you can run sudo a2enmod headers and restart Apache if it wasn’t already enabled. Most setups have this on by default, but it’s worth double-checking.
Next, add this configuration to your virtual host file (or .htaccess if you’re using that) to handle both the 503 response and CORS correctly:
# Send required CORS headers with EVERY response (including errors like 503) Header always set Access-Control-Allow-Origin "https://your-angular-app-domain.com" Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" Header always set Access-Control-Allow-Headers "Content-Type, Authorization" # Force OPTIONS preflight requests to return 503 with CORS headers RewriteEngine On RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=503,L] # Send 503 for all other requests RewriteRule ^(.*)$ - [R=503,L] # Optional: If you want Apache to serve a static maintenance page as a fallback # ErrorDocument 503 /maintenance.html
Key details to note:
- Using
Header always setis critical here. Withoutalways, Apache might skip adding CORS headers for error status codes like 503—exactly what was breaking your preflight checks. - The first rewrite rule targets OPTIONS requests specifically. Browsers send these before your actual API calls to check if the server allows cross-origin requests. We need to make sure this preflight gets the 503 + CORS headers, not a default 200 OK.
- For production, replace the example domain in
Access-Control-Allow-Originwith your actual Angular app domain (e.g.,https://myapp.com) instead of using a wildcard (which is fine for development but not secure for production).
To verify it’s working, run this curl command to test the OPTIONS preflight:
curl -X OPTIONS -I https://mywebsite/api/v1/loggedUser
You should see a 503 status code, plus all three CORS headers in the response. Once that checks out, your Angular app will receive the 503 properly and be able to route users to your maintenance page as intended.
内容的提问来源于stack exchange,提问作者drenda

