當網址使用了別的網域API資源時,瀏覽器會添加額外的標頭的機制,稱為CORS(Cross-Origin Resource Sharing(跨來源資源共用))在請求上,所以當網域上的網頁內容想要呼叫其他網站的資源的資源時就會觸發CORS。
觸發CORS時會在request添加Origin: http://bar.example
,response應該要有Access-Control-Allow-Origin
,且值應該要是"*"或 "http://bar.example" ,否則就算拿到了檔案瀏覽器也會直接擋掉。
用nginx處理最簡單的方法就是在location裡補上
add_header 'Access-Control-Allow-Origin' *;
這樣一來所有網站都能自由的使用這個資源
如果想要只限定在特定範圍,像是我們的網域與子網域,不想給隨便其他人使用,情況會複雜一點。
map $http_origin $cors {
'~*^https?://(account\.|asset\.|)dcreater\.com$' 'true';
}
map $cors $allow_origin {
'true' $http_origin;
}
map $cors $allow_methods {
'true' 'GET, OPTIONS, POST';
}
map $cors $allow_headers {
'true' 'User-Agent,Keep-Alive,Content-Type,Pragma,Cache-Control,Upgrade-Insecure-Requests';
}
解釋:
之後在location補上
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Credentials $cors;
add_header Access-Control-Allow-Methods $allow_methods;
add_header Access-Control-Allow-Headers $allow_headers;
完整設定檔
log_format logdata $Host | $request_uri;
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Credentials $cors;
add_header Access-Control-Allow-Methods $allow_methods;
add_header Access-Control-Allow-Headers $allow_headers;
server {
listen 80;
server_name dcreater.com;
location / {
resolver 127.0.0.11;
proxy_pass http://app:8000;
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Credentials $cors;
add_header Access-Control-Allow-Methods $allow_methods;
add_header Access-Control-Allow-Headers $allow_headers;
}
access_log /var/log/nginx/access.log logdata;
error_log /var/log/nginx/error.log;
}
server {
listen 80;
server_name account.dcreater.com;
location / {
proxy_pass http://app:8001;
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Credentials $cors;
add_header Access-Control-Allow-Methods $allow_methods;
add_header Access-Control-Allow-Headers $allow_headers;
}
}
server {
listen 80;
server_name asset.dcreater.com;
location / {
proxy_pass http://app:8002;
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Credentials $cors;
add_header Access-Control-Allow-Methods $allow_methods;
add_header Access-Control-Allow-Headers $allow_headers;
}
}
處理CORS解決API同源政策的問題,工作環境沒變動