nginx 跨域访问

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值