Misha Krul
Misha Krul

Reputation: 397

Reverse proxy CORS Configuration for NGINX

I have a nodejs server and react client app deployed to an ec2 instance. When I try to send a POST request to /api/emails route it returns a CORS / CORB error in the console.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9001/api/email. (Reason: CORS request did not succeed).

My app-server nginx configuration looks like:

server {
  listen 80;
  listen [::]:80;
  server_name ec2-52-202-82-153.compute-1.amazonaws.com;

  location / {
        proxy_pass http://127.0.0.1:9001/;
        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;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header 'Access-Control-Allow-Origin' '*';
        proxy_set_header 'Access-Control-Allow-Credentials' true;
     }
}

My app-client configuration looks like:

server {
  listen 80;
  listen [::]:80;
  server_name ec2-52-202-82-153.compute-1.amazonaws.com;

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

Upvotes: 1

Views: 3297

Answers (1)

Shawn C.
Shawn C.

Reputation: 6841

Via https://enable-cors.org/server_nginx.html

if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    #
    # Custom headers and headers various browsers *should* be OK with but aren't
    #
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    #
    # Tell client that this pre-flight info is valid for 20 days
    #
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
 }

if you put this in your app-server location it will see that it is a pre-flight request and return instantly with a 204. You will have to play with all of the different headers to get it to what you want.

Please Note This does assume that your nginx configs are setup up correctly as you have two server blocks with the same server_name

Upvotes: 1

Related Questions