nginx 跨域设置

  • 例如客户端的域名是 www.redis.com.cn , 而请求的域名是 www.264.cn
    如果直接使用ajax访问,会有以下错误
XMLHttpRequest cannot load http://www.264.cn/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.redis.com.cn' is therefore not allowed access.
  • 在服务器页面的Response header中加入如下内容,可以实现POST跨域。
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:POST');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');

Access-Control-Allow-Origin:* 表示允许任何域名跨域访问
如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名
例如:header('Access-Control-Allow-Origin:http://www.redis.com.cn');
  • 路由机设置:
server{
listen 8099;
server_name wdm.test.cn;
location / {

  // 没有配置OPTIONS的话,浏览器如果是自动识别协议(http or https),那么浏览器的自动OPTIONS请求会返回不能跨域
  if ($request_method = OPTIONS ) {
    add_header Access-Control-Allow-Origin "$http_origin";
    add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
    add_header Access-Control-Max-Age "3600";
    add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
    add_header Access-Control-Allow-Credentials "true";
    add_header Content-Length 0;
    add_header Content-Type text/plain;
    return 201;
  }
  add_header 'Access-Control-Allow-Origin' '$http_origin';
  add_header 'Access-Control-Allow-Credentials' 'true';
  add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
  proxy_pass http://127.0.0.1:8080;
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值