原文:http://www.neter8.com/server/42.html
當出現403跨域錯誤的時候 No 'Access-Control-Allow-Origin' header is present on the requested resource,需要給Nginx服務器配置響應的header參數:
在需要誇域的配置文件上加入以下代碼:
location / {
add_header Access-Control-Allow-Origin *;
}
Markup復制代碼
服務器默認是不被允許跨域的。給Nginx服務器配置Access-Control-Allow-Origin *后,表示服務器可以接受所有的請求源(Origin),即接受所有跨域的請求。也可以把*號替換成為域名如:http://www.neter8.com/ 這樣就只允許http://www.neter8.com/調用這個域名的數據。跨域成功!
Nginx允許多個域名跨域訪問:
*號如果不是我們想好的。我們可能定義多個域名訪問:
map $http_origin $corsHost {
default 0;
"~http://www.meishiq.com" http://www.meishiq.com;
"~http://m.meishiq.com" http://m.meishiq.com;
"~http://wap.meishiq.com" http://wap.meishiq.com;
}
server
{
listen 80;
server_name www.neter8.com;
root /usr/share/nginx/html;
location /
{
add_header Access-Control-Allow-Origin $corsHost;
}
}
Markup復制代碼
通過map就可以實現定義的多個域名訪問了。
原文鏈接:http://www.neter8.com/server/42.html