apache tutorial - Enable CORS - apache - apache web server - apache server - apache2
Enable CORS in Apache
- To enable Cross-Origin Resource Sharing (CORS) in Apache you'll need to set at least one HTTP header which changes it (the default behaviour is to block CORS).
- In the following example, we're going to be setting this HTTP header inside .htaccess, but it can also be set in your site .conf file or the Apache config file.
- Regardless of how your configuration looks like, you can set the relevant HTTP headers in any Apache config block, i.e. <VirtualHost>, <Directory>, <Location>, and <Files>.
- There are a few CORS related HTTP headers which you can return in the response:
- Some of the above are required for "preflight" requests. Some HTTP clients (namely, modern browsers) perform a request before your desired request just to see if they have authorisation to make the actual request on the server.
- The main HTTP header is Access-Control-Allow-Origin and that's we're going to set. However, the same principle applies pretty much to all of them (you just need to know what to return).
- The following example sets the required HTTP header within a <Directory> config block to enable an SSL protected client Full Qualified Domain Name (FQDN):
- After we've set this on the server, we can now perform a request from https://my.client.domain to our server and it should respond.
Note: A lot of people use Access-Control-Allow-Origin: "*" which is a wildcard, to mean requests from ALL domains should be accepted. This is usually ill-advised unless you're running some sort of a public API or repository of files. Also, please note the context of you HTTP header setting. You might want to allow HTTP requests for an API, but not for "hotlinking" images etc. You can set this header anywhere you want within your Apache config flow to only set it in specific situations. For example, the following would only set the CORS HTTP header when the requested path is not a file or directory (suits a public API which disallows image hotlinking):
Prerequisites
You've got to have mod_headers installed and enabled: a2enmod headers