How to Fix Apache CORS Header Configuration Error
In this tutorial, you'll learn about How to Fix Apache CORS Header Configuration Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Browser console shows Access to XMLHttpRequest at 'https://api.example.com/data' from origin 'https://app.example.com' has been blocked by CORS policy — Apache is not sending the required CORS headers.
The Problem
Access to XMLHttpRequest at 'https://api.example.com/data'
from origin 'https://app.example.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Step-by-Step Fix
Step 1: Enable mod_headers
sudo a2enmod headers
sudo systemctl restart apache2
Step 2: Add CORS headers in virtual host
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
Step 3: Handle preflight requests
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
# Or use Header always for OPTIONS
<LocationMatch "^/api/">
Header always set Access-Control-Allow-Origin "https://app.example.com"
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type"
# Handle preflight
Header always set Access-Control-Max-Age "86400"
</LocationMatch>
Step 4: Restrict CORS to specific origins
SetEnvIf Origin "^(https://app\.example\.com)$" CORS_ORIGIN=$1
Header set Access-Control-Allow-Origin "%{CORS_ORIGIN}e" env=CORS_ORIGIN
Step 5: Test CORS headers
curl -H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: GET" \
-X OPTIONS \
-v https://api.example.com/api/data 2>&1 | grep -i "access-control"
Prevention Tips
- Never use
Access-Control-Allow-Origin: *with credentials - Always handle OPTIONS preflight requests explicitly
- Restrict allowed origins in production to specific domains
- Cache preflight responses with Access-Control-Max-Age
Common Mistakes with cors header
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world APACHE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro