即使 Nginx 存在 CORS 问题,仍然可以获取数据

即使 Nginx 存在 CORS 问题,仍然可以获取数据

我正在尝试调试 CORS 问题。这是我使用的配置http://www.test-cors.org/测试我的 Nginx 规则。当我使用的方法是 OPTIONS 时,我在浏览器的控制台中收到以下消息。但我仍然收到了非常奇怪的数据

Failed to load http://www.example.com:8009/testcors: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.test-cors.org' is therefore not allowed access.

如果我使用的方法是 GET,我会收到以下消息。我还会获取数据

Failed to load http://www.example.com:8009/testcors: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.test-cors.org' is therefore not allowed access.

这是我更新的 nginx 配置,第三次更新,我将其放在一个新文件中。

  ❯ cat /usr/local/etc/nginx/nginx-mini.conf
  worker_processes  1;
  worker_rlimit_nofile 15000;

  error_log  logs/error.log;
  error_log  logs/error.log  notice;
  error_log  logs/error.log  info;

  events {
   worker_connections  5000;
   accept_mutex off;
  }


  http {
   include       mime.types;
   default_type  application/octet-stream;
   proxy_cookie_path / "/; HTTPOnly; Secure";

   types_hash_max_size 4096;
   access_log off;
   sendfile off;
   sendfile_max_chunk 512k;
   tcp_nopush      off;
   tcp_nodelay      on;
   output_buffers 1 3m;

   open_file_cache          max=10000 inactive=5m;
   open_file_cache_valid    2m;
   open_file_cache_min_uses 1;
   open_file_cache_errors   on;

   gzip on;
   gzip_disable "MSIE [1-6]\.(?!.*SV1)";
   gzip_http_version  1.1;
   gzip_comp_level    5;
   gzip_min_length    256;
   gzip_proxied       any;
   gzip_vary          on;

   gzip_types
     application/atom+xml
     application/javascript
     application/json
     application/rss+xml
     application/vnd.ms-fontobject
     application/x-font-ttf
     application/x-javascript
     application/x-web-app-manifest+json
     application/xhtml+xml
     application/xml
     application/xml+rss
     font/opentype
     image/svg+xml
     image/x-icon
     text/css
     text/javascript
     text/js
     text/plain
     text/x-component
     text/xml;

   # CORS
   map $http_origin $allow_origin {
     default "";
     ~example.com "$http_origin";
   }

   server {
     listen 8009;
     server_name www.example.com;
     access_log /var/log/nginx/access.log;
     error_log /var/log/nginx/error.log debug;

     location /testcors {
        if ($request_method = 'OPTIONS') {
           add_header 'Access-Control-Allow-Origin' $allow_origin;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Max-Age' 60;
           add_header 'Content-Type' 'text/plain; charset=utf-8';
           add_header 'Content-Length' 0;
           return 204;
        }
        if ($request_method = 'POST') {
           add_header 'Access-Control-Allow-Origin' $allow_origin;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }

        if ($request_method = 'GET') {
           add_header 'Access-Control-Allow-Origin' $allow_origin;
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
           add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
           add_header GETMETHOD accessed;
           add_header Content-Type "application/json; charset=utf-8";
        }

       add_header Content-Type "application/json; charset=utf-8";
       return 200 '{"code": 200, "reason": "Testing CORS ..."}';
     }
   }
  }

我是这样开始的

sudo nginx -c /usr/local/etc/nginx/nginx-mini.conf

ps ax | grep nginx 显示进程

31528   ??  Ss     0:00.00 nginx: master process nginx -c /usr/local/etc/nginx/nginx-mini.conf
31529   ??  S      0:00.00 nginx: worker process
31787 s003  R+     0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn nginx

netstat 显示与我的 nginx 关联的 tcp 端口

❯ netstat -na|grep 8009
tcp4       0      0  *.8009                 *.*                    LISTEN

IP地址正确

 ❯ ping www.example.com
 PING airborne.gogoinflight.com (127.0.0.1): 56 data bytes
 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.042 ms
 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.067 ms
 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.132 ms

我确保使用 curl 连接到我自己的本地运行的 nginx 服务器

❯ curl http://www.example.com:8009/testcors
{"code": 200, "reason": "Testing CORS ..."}%

结果还是一样(chrome dev tools 的截图)https://i.stack.imgur.com/CB67D.jpg

答案1

问题在于您没有在您的 中发送 CORS 标头location /testcors

server对于任何其他位置,您只能在区块中发送这些内容。

原因是add_header较低级别块中的指令完全覆盖更高级别块中的那些。因此,由于您已add_header在 中使用location,因此还必须add_header再次包含所有其他指令。

为了保持配置 DRY,你应该考虑制作include文件其中包含通用add_header指令,然后include位于配置中的每个相关点。

答案2

哇哦!!!我终于让它工作了!!!我了解到,如果与源不匹配,我们必须告诉 nginx 我们想要做什么。我对 Nginx 的第一印象是,如果域名不同,它会自动阻止它们。我发现的 99% 的示例都没有提到这一点。

# CORS
map $http_origin $allow_origin {
  default "blocked";
  ~example.com "allowed";
}

map $allow_origin $origin_is_allowed {
  allowed $http_origin;
}

location ~ /getapi/?(?<capture>.*) {
   if ($allow_origin = 'allowed') {
      add_header 'Access-Control-Allow-Origin' "$origin_is_allowed";
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
      add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
      add_header Content-Type "application/json; charset=utf-8";
      proxy_pass http://localhost:7777/api/$capture;
   }
   if ($allow_origin = 'blocked') {
      add_header Content-Type "text/plain";
      return 403 "Your domain is not allowed!";
   }
}

这是 test-cors.org 失败:)https://i.stack.imgur.com/3kKXY.png 之前即使有 cors 错误也能获取数据

相关内容