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
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]

1 comment:

Dhiya L said...

Thanks for sharing the valuable information here. So i think i got some useful information with this content. Thank you and please keep update like this informative details.

Java Training in Chennai