CORS configuration

Last change on 2023-03-28 • Created on 2023-03-28 • ID: MA-80DBF

Control which sources are permitted to access APIs or interfaces running under a different domain. The following settings are relevant here:

  • Access-Control-Allow-Methods => which methods (GET, POST etc.) should be allowed

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

  • Access-Control-Allow-Origin => from which domains is the access permitted

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

  • Access-Control-Allow-Headers => which headers may be transmitted during the request (optional)

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

In addition, CORS preflight requests must be allowed. Here the browser carries out corresponding OPTIONS requests in order to check in advance whether the API is configured correctly and access is permitted. An HTTP 200 should also be returned here as a status code.

Here is an example. Let's assume that there is access to https://testen.de, which integrates an external API https://api.example.com. In the example, a content-type header is also transmitted.

In this situation, you would need to create or edit an .htaccess file in the start directory of api.example.com. You could structure this like what you see below. (Please pay attention to the comments):

# Here you have to provide the "supported" HTTP methods. OPTIONS shall *always* be included, you can find further information regarding this setting at:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
# This should be configured according to your requirements:
header always set Access-Control-Allow-Methods OPTIONS,GET,POST,PUT

# Here you have to specify, from which domains the access is permitted. It's supported to specify multiple domains comma separated:
header always set Access-Control-Allow-Origin https://testen.de

# OPTIONAL allowing further custom HTTP headers:
header always set Access-Control-Allow-Headers Content-Type

# The HTTP Status Code shall only be enforced for preflight (OPTIONS) requests. When configuring this for all domains, it would harm the functionality of the website.
<If "%{REQUEST_METHOD} == 'OPTIONS'">
        # Change the HTTP Status Code to 200 (successfully)
        RewriteRule ^ - [R=200,L]
</If>

The interface at https://api.example.com can then be accessed easily within the application https://testen.de using CORS.