Saturday, July 26, 2014

Configuring Apache to return CORS headers for Drupal Services

Here's what I did to configure Apache to return the proper CORS headers for my webapp consumption which is written in AngularJS:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header always set Access-Control-Allow-Headers "accept, content-type"
Header always set Access-Control-Allow-Credentials "true"

That can be set in the VirtualHost tags for your server instance. Please note that Access-Control-Allow-Origin value shouldn't be set to * in a production environment. This should only be done for testing environments. The mod_headers module must be enabled in Apache for this configuration to work.

Having these options should be sufficient. But since I'm using Drupal 7 Services, it doesn't play well with pre-flight call which uses HTTP OPTIONS method. Drupal services will return a 404 even if the correct endpoint is specified when OPTIONS method is used.

Here's the additional config using mod_rewrite to return HTTP 200 for all OPTIONS requests:

RewriteEngine On
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]