Showing posts with label apache2. Show all posts
Showing posts with label apache2. Show all posts

Wednesday, May 7, 2014

Apache CORS Headers

It is possible to add multiple domains by using the following:
Header set Access-Control-Allow-Origin "http://domain1.com"
Header add Access-Control-Allow-Origin "http://domain2.net"
Header add Access-Control-Allow-Origin "http://domain3.org"
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)://(domain1.com|domain2.net|domain3.org)$" RequestOrigin=$0
Header always set Access-Control-Allow-Origin %{RequestOrigin}e env=RequestOrigin
This will return http://domain2.net if the request has an Origin of http://domain2.net. 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