【问题标题】:Reverse proxy CORS Configuration for NGINXNGINX 的反向代理 CORS 配置
【发布时间】:2020-08-06 14:47:00
【问题描述】:

我有一个 nodejs 服务器和响应客户端应用程序部署到一个 ec2 实例。当我尝试向 /api/emails 路由发送 POST 请求时,它会在控制台中返回 CORS / CORB 错误。

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).

我的应用服务器 nginx 配置如下:

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;
     }
}

我的应用客户端配置如下:

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;
        }
}

【问题讨论】:

    标签: nginx proxy configuration cors


    【解决方案1】:

    通过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;
     }
    

    如果你把它放在你的app-server 位置,它会看到它是一个飞行前请求,并立即返回一个 204。你必须使用所有不同的标头来获得你想要的。

    请注意,这确实假设您的 nginx 配置设置正确,因为您有两个具有相同 server_name 的服务器块

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 2017-12-01
      • 2014-05-01
      • 2023-04-03
      • 2015-02-12
      相关资源
      最近更新 更多