
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 도끼 | 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
컬을 사용하여 로컬로 실행되는 nginx 서버에 연결하고 있는지 확인했습니다.
❯ curl http://www.example.com:8009/testcors
{"code": 200, "reason": "Testing CORS ..."}%
결과는 여전히 동일합니다(Chrome 개발 도구의 스크린샷).https://i.stack.imgur.com/CB67D.jpg
답변1
문제는 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 오류가 있어도 데이터를 얻을 수 있었습니다.