How to Set CORS Headers for Hosting Files

Avatar
Martin Večeřa

Sometimes, web applications need to access files (images, videos, data files etc.) from other servers. This has many potential security risks like malicious code misusing your cookies to access the application. This is why it is important to know how to set CORS headers on the server.

CORS (Cross-Origin Resource Sharing) headers prevent arbitrary code accessing data on random servers. Unfortunatelly, this can cause difficulties for the valid usage too.

CORS request

When you, for instance, want to host a custom map layer for use in Lumeer. You are most likely to hit an error that the file access is blocked by CORS.

To make that file hosting to Lumeer or any other web application possible, you need to have a permission from the server owner. You can either ask them to include https://get.lumeer.io among the allowed domains, or, in case you manage the server, you can set that on your own.

How to Set CORS Headers on Apache

Simply add the following policy to your .htaccess file in the directory from which you host the files.

The trick is that the Allow-Control-Allow-Origin header can carry only one value at a time. We do not want to introduce the risk of setting it to * (allow everything). As this would be equal to not using CORS at all.

We also need to allow all headers that the application might send (as we already know it is a safe application).

For hosting files for Lumeer, the rule looks like follows:

<IfModule mod_headers.c>
    SetEnvIf Origin "https://get\.lumeer\.io$" AccessControlAllowOrigin=$0
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header add Access-Control-Allow-Headers * env=AccessControlAllowOrigin
    Header merge Vary Origin
</IfModule>

How to Set CORS Headers on NGINX

The desired goal is the same. The configuration looks a bit different but it is still self explaining:

server {
  listen        80;
  server_name   api.test.com;


  location / {

    set $cors 0;
    if ($http_origin ~ '^https://get\.lumeer\.io)') {
        set $cors 1;
    }
    if ($request_method ~* "(GET|OPTIONS)") {
        set $cors 1$cors;
    }

    # Simple requests
    if ($cors = 11) {
      add_header "Access-Control-Allow-Origin" "$http_origin";
      add_header "Access-Control-Allow-Headers" "*";
    }

    ....
    # Handle request
    ....
  }
}