nginx允许跨域访问配置
一、什么是跨域[转]
简单地理解就是因为JavaScript同源策略的限制,a.com域名下的js无法操作b.com或是c.a.com域名下的对象。
同源是指相同的协议、域名、端口。特别注意两点:
1、如果是协议和端口造成的跨域问题"前台"是无能为力的
2、在跨域问题上,域仅仅是通过"协议+域名+端口"来识别,两个不同的域名即便指向同一个ip地址,也是跨域的。
二、如何配置nginx跨域
只需要在Nginx的server下的location配置文件中配置以下参数:
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET,PUT,DELETE,POST,OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Content-MD5';
}
解释:
1. Access-Control-Allow-Origin
服务器默认是不被允许跨域的。给Nginx服务器配置Access-Control-Allow-Origin *后,表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求。
2. Access-Control-Allow-Headers 是为了防止出现以下错误:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
这个错误表示当前请求Content-Type的值不被支持。其实是我们发起了"application/json"的类型请求导致的。这里涉及到一个概念:预检请求(preflight request),请看下面"预检请求"的介绍。
3. Access-Control-Allow-Methods 是为了防止出现以下错误:
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
发送"预检请求"时,需要用到方法 OPTIONS ,所以服务器需要允许该方法。
评论