enabling CORS on Apache

Many people struggle to get CORS (Cross-Origin Resource Sharing) enabled on their site to allow transmission of JSON, XML, or some other sort of data from one script to another, running on different domains. Simply adding Header always set Access-Control-Allow-Origin “*”  to .htaccess doesn’t do the trick for me.

Here’s what worked for me on Apache version 2.4.33…

Note: The Apache modules mod_headers and mod_rewrite must be enabled.

Add this to an .htaccess file in the directory you want to expose. The part of the solution most elusive was the HTTP 200 request code response. Without this part, extra-origin hosts could not connect.


Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

# Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
RewriteEngine On
RewriteRule ^(.*)$ $1 [R=200,L]

After implementation, the HTTP response header looks like this:

HTTP/1.1 200 OK
Date: Thu, 14 Jun 2018 00:00:00 GMT
Server: Apache
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Max-Age: 1000
Access-Control-Allow-Headers: x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Cache-Control: max-age=3600
Expires: Thu, 14 Jun 2018 16:30:44 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
Content-Type: text/html; charset=UTF-8

Here are some great troubleshooting tools for CORS debugging and verification:

Tagged with: , , , ,
Posted in how-to, resources, unsorted