Different Access-Control-Allow-Origin for multiple folders

Hey All!

I have the following folder structure I want to restrict via CORS:

data
    folder1
         subfolder1
               file1.json
               file2.json
               file3.json
         subfolder2
               file1.json
               file2.json
               file3.json
    file1.json
    file2.json

Conditions:

  • any json file in data is freely accesible
  • any json file in subfolder1 is restricted to only two domains

Can you please help me write the netlify.toml file to answer to above conditions?

Not sure this will work?

[[headers]]
    for="/data/*.json"
         [headers.values]
         Access-Control-Allow-Origin = "*"
[[headers]]
    for="/data/folder1/subfolder1/*.json"
         [headers.values]
         Access-Control-Allow-Origin = "http://google.com/"
         Access-Control-Allow-Origin = "124.125.126.127"
[[headers]]
    for="/data/folder1/subfolder2/*.json"
         [headers.values]
         Access-Control-Allow-Origin = "http://google.com/"
         Access-Control-Allow-Origin = "124.125.126.127"

Thank you!

Hi @webdevst,

While the configuration you tried above is supported, what you’re trying is not. let me explain.

The syntax is correct and expected to work, but you can’t send multiple CORS headers for the same request. Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed - HTTP | MDN

Hi @hrishikesh !

Thank you for your reply!

Do you happen to have any suggestions for allowing 1 domain in Access-Control-Allow-Origin, while also supporting localhost for development?

The MDN documentation answers your question:

specifically, this part:

<origin>

Specifies an origin. Only a single origin can be specified. If the server supports clients from multiple origins, it must return the origin for the specific client making the request.

In other words, you’d have to check the origin header of the request and respond with a single Access Control Origin header for that request.