If you’re building an web app that uses JavaScript to pull data from a remote server, you often run into CORS issue. Browsers report an error similar to the one I pasted below:
XMLHttpRequest cannot load http://my_domain.com/path. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://some_other_domain.com/some_path' is therefore not allowed access.
Modify Apache configuration to support Cross-Origin requests:
Step 1: Enable apache module (mod_headers) that allows to add headers in your httpd.conf file
LoadModule headers_module modules/mod_headers.so
Step 2: Add the following entry in your virtual host configuration
Header always set Access-Control-Allow-Origin "*"
Step 3: Limit the methods allowed (this should be added right below the config entry from Step 2).
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Step 4: Restart Apache and verify
It is not a good practice to allow all domains (Step 1 with entry "*") and typically we try to allow only sub-domains or selective domains. Below are some examples of how to allow sub-domains or selected list of domains.
For Sub-Domains
SetEnvIf Origin "^(.*\.mydomain\.com)$" ANY_SUB_DOMAIN=$1
Header always set Access-Control-Allow-Origin "%{ANY_SUB_DOMAIN}e" env=ANY_SUB_DOMAIN
For Selected List of Domains:
SetEnvIf Origin "http(s)?://(www\.)?(domaina.com|domainb.com)$" AllowDomain=$0$1
Header always set Access-Control-Allow-Origin %{AllowDomain}e env=AllowDomain
Note:
1. Don't forget to enable mod_setenvif
LoadModule setenvif_module modules/mod_setenvif.so
2. Don't forget to do an apache restart after making config changes.