Set Access-Control-Allow-Origin (CORS) headers in Apache vhost or htaccess

Here’s a quicky copy/paste you can use when you need to set Access-Control-Allow-Origin headers in an Apache configuration, or in your .htaccess file.

Just a quick reminder on Access-Control-Allow-Origin first:

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow XMLHttpRequest to make cross-domain requests.

[…]

CORS gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

Access-Control-Allow-Origin

So, in order to use it, you need to set the correct headers. In your .htaccess or Apache webserver configuration, add headers like these.

Header Set Access-Control-Allow-Origin "https://your.external.resource.tld"

You set this header on the server that hosts the resource. It tells the browser which origin is allowed to read the response: in this case, only a page served from “https://your.external.resource.tld ” may make the cross-origin request (think AJAX requests or webfonts). Mind the protocol, this would – in this case – only allow that exact HTTPS origin. The same host over plain HTTP would be a different origin and would still be blocked.

If you want to completely disable CORS (which I wouldn’t recommend, but is useful for testing purposes):

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

But as mentioned above, it’s safer to actually set the Access-Control-Allow-Origin to contain the list of domains that your application can request data from (or send data to).

If you have multiple domains and want to set a CORS header based on that domain, you can use a cool hack like this:

SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin

Because there can only be one CORS domain in the header, you’ll need to get creative if you want to use this on multiple domains.