Nginx设置多个域名跨域

如果需要多个域名服务跨域或子域名跨域,如下面这样的.

add_header Access-Control-Allow-Origin *.pythonxyz.com;

一种办法是支持所有域名,如:

add_header Access-Control-Allow-Origin *;

但这样不安全,如果是指定列表,可以如下面这样设置.

location /  {
  set $cors "";
  if ($http_origin ~* (\.pythonxyz\.com|\.doxyz\.com)) {
      set $cors "true";
  }

  proxy_pass http://backend:10005/pythonxyz/;

  if ($cors = "true") {
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
  }
}

这样设置就OK~

还有一种设置是使用Nginx的map.如下

map $http_origin $DO_CORS {

  # indicates all map values are hostnames and should be parsed as such
  hostnames;

  # default value
  default 'false';

  # all your domains
  localhost          'true';
  www.pythonxyz.com 'true';
  www.doxyz.com  'true';
}

今天遇到错误

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.

已经添加Access-Control-Allow-Origin,Access-Control-Allow-Methods

解决办法:

Access-Control-Allow-Headers里添加X-Requested-With.

add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type,X-Requested-With';

根据需要,还可以添加上Access-Control-Allow-Headers, Authorization

还有一种情况,上面都已经设置,还是报错。如果是JQuery,有这说明。

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

解决办法:

$http.post(url, data, {
    headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});


评论(0条)

暂时还没有评论,第一个来评论吧!


我要发表看法

引用   粗体   链接   缩进  

最近编辑

热门标签