Return to site

Apache CORS (Cross-Origin-Resource-Sharing)

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 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' 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/

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\.)?(|$" AllowDomain=$0$1
Header always set Access-Control-Allow-Origin %{AllowDomain}e env=AllowDomain

1. Don't forget to enable mod_setenvif


LoadModule setenvif_module modules/


2. Don't forget to do an apache restart after making config changes.

All Posts

Almost done…

We just sent you an email. Please click the link in the email to confirm your subscription!