CORS with Apache, mod_headers, and .htaccess

CORS, or Cross-Origin-Resource-Sharing, describes a protocol for securely sharing resources between different websites. By default, web browsers do not allow web pages to access external resources via AJAX as a security measure. CORS allows websites to load external resources, if the remote server explicitly allows it via a set of headers.

This issue can also pop up if you are working locally, and you are viewing a HTML file via the file:// protocol and loading resources via the http:// protocol.

Apache mod_headers provides an easy way to implement CORS and add the appropriate headers. Of course, you may want to dynamically server the CORS headers, but this is dead-simple.

Simply add the following to a file called ‘.htaccess’, and you will be able to access the resources in that directory (and all nested directories) via other websites.

Header add Access-Control-Allow-Origin "*"

To verify the header is present, use curl with the -I (capital i) flag to display the headers. You should see the “Access-Control-Allow-Origin: *” header.

Nick-Stielaus-MacBook-Pro: nstielau$ curl -I
HTTP/1.1 200 OK
Date: Mon, 03 Jan 2011 20:33:15 GMT
Server: Apache/2.2.15 (Unix) mod_ssl/2.2.15 OpenSSL/0.9.8l DAV/2 PHP/5.3.3
Last-Modified: Fri, 12 Nov 2010 03:11:29 GMT
ETag: "7bcc62-13309-494d272541a40"
Accept-Ranges: bytes
Content-Length: 78601
Access-Control-Allow-Origin: *
Content-Type: application/javascript

If this isn’t working, it may mean that a) you don’t have mod_headers loaded by Apache, or b) that you have .htaccess file overrides turned off.

2 thoughts on “CORS with Apache, mod_headers, and .htaccess

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>