Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx reverse proxy to avoid cors error with localhost

Tags:

cors

nginx

I am using a gulp server for local front end development, the application I connect to is running on another server, both front and back end.

The gulp server is running on localhost:1340. The api is at https://aaa.bbb.com/api

I get the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So I am trying to set up a reverse proxy server using nginx, so that I will start up an nginx server on localhost:8001 and it acts as the connection between the gulp server and the api.

Here is the set up from nginx.conf

server { # simple reverse-proxy
    listen       8001;
    server_name  localhost;
    # access_log   logs/domain2.access.log  main;


    location / {
      proxy_pass      http://localhost:1340;
      proxy_set_header Host $http_host;
      add_header Access-Control-Allow-Origin *;


      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-NginX-Proxy true;

    }
    location /api/ {
      proxy_pass      https://aaa.bbb.com/api/;
      add_header Access-Control-Allow-Origin *;

      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;



      proxy_redirect off;

    }
  }

But what happens is when i point to localhost:8001, i still get the cors errors, it is just passing the gulp server content. when i point to localhost:8001/api/ it passes the content of the external server, with the front end that is deployed there.

The behaviour that I need is my local ui pointing to the external server, so that I can see changes I make locally in the ui. There is a work around using chrome with security disabled, but this means I can't check other browsers for changes that I make.

Any help/ideas would be much appreciated.

like image 543
santiago Avatar asked Sep 24 '26 09:09

santiago


1 Answers

I had the exact same problem and stumbled upon this question (without answer) so I just thought why not just give it a try. And it worked directly for me. No header settings or anything - just the proxy_passes added to a default nginx configuration. This is what I did:

server {
    listen       8001;
    server_name  localhost;

    location / {
        proxy_pass http://127.0.0.1:1340;
    }

    location /api {
        proxy_pass https://aaa.bbb.com/api;
    }
}

I suspect that one or two of the headers you set are causing the problem. You just want a straight forward reverse proxy so that the browser doesn't suspect that there are several domains behind it.

like image 77
froderik Avatar answered Sep 26 '26 02:09

froderik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!