Apache – Enable Cross-origin resource sharing CORS

Long time ago, we talked about using JSONP to tackle to cross domain ajax issue.
jQuery & JSON – Make Cross Domain Request Using jQuery.getJSON() with JSONP

But this requires server side coding. If you are allow to edit the Apache config, you can simply Enable the CORS (Cross-origin resource sharing) in the VirtualHost file as follow.

1. Enable the mod_headers in Apache by entering the following command in shell.

a2enmod headers

 

2. Edit the VirtualHost file and add the Access-Control-Allow-Origin entry inside <Directory>.

...
<Directory "C:\Users\user\Documents\GitHub\drupal7">
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  Allow from all
  # Allow any domain
  Header add Access-Control-Allow-Origin "*"
  # OR allow specific domains
  Header add Access-Control-Allow-Origin "http://domain1.com"
  Header add Access-Control-Allow-Origin "http://domain2.com"
  Header add Access-Control-Allow-Origin "http://domain3.com"
</Directory>
...

 

3. Restart the Apache service.

/etc/init.d/apache restart

 

Done =)

Reference:

One thought on “Apache – Enable Cross-origin resource sharing CORS”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.