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

Tired of the privacy invasion of browsers? Worried about the risk of seeing ads everywhere? Give the Brave Browser a try. All Chrome extensions are compatible. None of the telemetry. Auto-blocks ads and still support content creators like me.

Download the Brave browser now »

Profile image of Mattias Geniar

Mattias Geniar, March 16, 2016

Follow me on Twitter as @mattiasgeniar

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"

The above would allow the site that sends that header, to request resources (like AJAX requests or webfonts) from the “https://your.external.resource.tld” domain. Mind the protocol, this would – in this case – only allow HTTPS requests. HTTP requests 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 create if you want to use this on multiple domains.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.