I have a simple local html with some JS that I currently serve via Docker-nginx on localhost:8080 via
docker run -it --name nginx_ol -v ${PWD}:/usr/share/nginx/html:ro -p 8080:80 -d nginx:alpine
The JS should fetch a JPG from an ("upstream"?) server like so
var url = http://example.com/foo/bar.jpg
fetch(url, {method: 'GET', mode:'cors'})
The server is not set up to send the appropriate CORS-headers. Trying to fetch the image this way results in [...] Origin localhost:8080 is not allowed by Access-Control-Allow-Origin
as expected.
In my understanding, I have to
- configure nginx to reverse proxy the resource to my localhost while adding the necessary CORS headers
- Make the request to the proxied location instead
I.e. proxy the image location at http://example.com/foo/bar.jpg
to http://localhost/foo/bar.jpg
and adjust the fetch URL accordingly.
Being completely green in terms of nginx/proxies, I've read the docs for adding CORS headers for servers I control, and seen examples for adding CORS headers to proxy servers like so.
If I wanted to proxy requests to localhost:8080/foo
to http://example.com/foo
, I'd expect something like the following to do the job:
server {
listen 80;
server_name localhost;
add_header 'Access-Control-Allow-Origin';
add_header ...
location / {
proxy_set_header Host $host;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control...
proxy_redirect off;
proxy_set_header host $host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
proxy_pass http://example.com/;
}
}
For the request URL localhost:8080/foo/bar.jpg
, I'm getting GET 404 (Not found)
, which tells me that nothing like that is happening.
I'm sorry that this is a matter of basic misunderstanding, but I'm sure users like me who struggle with getting a proxy up and running would benefit from any nudge in the right direction :)