Wednesday, May 7, 2014

Apache CORS Headers

It is possible to add multiple domains by using the following:
Header set Access-Control-Allow-Origin ""
Header add Access-Control-Allow-Origin ""
Header add Access-Control-Allow-Origin ""
However, it doesn't work entirely as expected and it also exposes all your API clients to anyone interested. Not a big deal, but why expose more info than necessary?

So, to only have valid requests return one single domain (the accepted Origin) we can configure Apache to dynamically check and return only one permitted domain:
SetEnvIf Origin "(http|https)://(||$" RequestOrigin=$0
Header always set Access-Control-Allow-Origin %{RequestOrigin}e env=RequestOrigin
This will return if the request has an Origin of If the request has an origin that isn't matched by the regular expression in the SetEnvIf command, then it will not return any Access-Control-Allow-Origin header at all!

Some other headers I always include:
Header set Access-Control-Allow-Methods 'GET,PUT,POST,DELETE,OPTIONS'
Header set Access-Control-Allow-Credentials true