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

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

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.