nginx跨域访问配置内容:
server
{
listen 80;
index index.html index.htm index.php;
root /usr/local/www/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
location /
{
try_files $uri $uri/ /index.php$is_args$query_string;
index index.php index.html index.htm;
}
location ~ .*\.(php|php5)?$
{
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, PUT,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';
if ($request_method = 'OPTIONS') {
return 204;
}
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/www/$fastcgi_script_name;
include fastcgi_params;
}
}
主要是在我们一般配置上加上
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, PUT,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';
if ($request_method = 'OPTIONS') {
return 204;
}
跨域一般如果发出 PUT DELETE 等 请求 或 请求 头部(header)有非标准的内容时(例如请求头加上 access-token : xxxx)等,都会请求多一次 OPTIONS 请求,目的是先询问nginx 是否允许某些危险动作,所以我们只要允许 OPETION 返回相应 配置的响应头就可以了,
ps:
还有一点是:我的
if ($request_method = 'OPTIONS') {...return 204;} 写在了 php文件上面,所以它只有访问php 时才生效,包括 localhost 也不生效,虽然是默认 index.php
例如
function test(){
var request = new XMLHttpRequest();
//这个是能生效的
request.open("PUT", "http://192.168.99.100:4080/index.php");
//这个不能生效
//request.open("PUT", "http://192.168.99.100:4080");
request.onreadystatechange=function()
{
if (request.readyState==4)
{
if(request.status==200){
console.log("上传成功");
}else{
console.log("上传失败,检查上传地址是否正确");
}
}
}
request.send();
}
因为
http://192.168.99.100:4080 就是走到 location / {} 上去了。nginx 的正则也是个问题。
OPT