[Apache] CORS header

What is CORS ?

CORS or cross-origin resource sharing is a mechanism that allows resources on a web page to be requested from a different domain than the page origin. To do that the CORS mecanism use a specific header: Access-Control-Allow-Origin.

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example XMLHttpRequest and Fetch follow the same-origin policy. This header allow you to customize this behavior.

Authorize a domain

Just add to your apache configuration:

Header set Access-Control-Allow-Origin "https://www.domain.com"

Authorize multiple domains

Access-Control-Allow-Origin can take only one value. You could use the value * but that ugly and defeat the whole purpose of filtering request domain origin.

But with a little trickery you can do that:

SetEnvIfNoCase Origin "https?://(domain\.com|staging\.domain\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO

This regex use the content of the Origin header and define a matching Access-Control-Allow-Origin value. Here we authorize both the http and https versions of domain.com and staging.domain.com to load ressources from our domain.

Further Reading and sources