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.
## ENABLES CORS ## 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 RewriteCond %{REQUEST_METHOD} OPTIONS 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:
- https://www.test-cors.org – use this to make sure an external domain can pull data from your host
- https://resttesttest.com/ – similar to the service above, but provides the data received from your site and some other options
- https://headers.cloxy.net/ – use this to view your HTTP headers.