How to add a CORS header in a proxy?

I have a URL https://example.com/file.txt which serves a file. Access to the file is authenticated via a bearer (a key in the headers).

The problem is that example.com does not sets the CORS header and I cannot access file.txt from JavaScript in a browser.

One possibility is to fix the site. This is not readily feasible.

One other possibility I was considering is to use caddy as a proxy which would

  • pass the request to the server (together with all the headers, including the authentication one above)
  • provide in return to the browser CORS headers which would allow for access from the browser

I was hoping that

proxy / https://example.com {
    transparent
}
cors
log stdout
errors stderr
}

would be enough but I guess that cors is for cases when caddy acts as the primary server (and not a proxy).

Is there a way to achieve such CORS-enabling proxification?

EDIT: I see that a “welcome back” header is added to the post:

Yes, I am comniog back to caddy after two years of wandering in less friendly waters :slight_smile:

Hi @WoJ, indeed, welcome back!

I’m fairly sure you should be able to just set Access-Control-Allow-Origin as a header downstream from the proxy.

proxy / https://example.com {
  transparent
  header_downstream Access-Control-Allow-Origin "*"
}

That should have the proxy tack on that header whenever it sends the response back to the client.

2 Likes

Ha, I think Discourse added this feature recently. I didn’t know that members could see the banners about themselves, too! That’s kinda funny.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.