设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 服务器 > Nginx

如何配置 Nginx 以便支持 CORS 跨域

时间:12-14来源:作者:点击数:
城东书院 www.cdsy.xyz

首先创建一个将来被 include 的 nginx 配置文件片段 cors-include.conf,然后在 nginx 的配置文件中引用这个文件:

location / {
  include cors-include.conf;
  ...
}

cors-include.conf 的内容如下:

#
# Wide-open CORS config for nginx
#
if ($request_method = 'OPTIONS') {
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, MKCOL, COPY, MOVE';
  #
  # Custom headers and headers various browsers *should* be OK with but aren't
  #
  add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  #
  # Tell client that this pre-flight info is valid for 20 days
  #
  add_header 'Access-Control-Max-Age' 1728000;
  add_header 'Content-Type' 'text/plain charset=UTF-8';
  add_header 'Content-Length' 0;
  return 204;
}
if ($request_method ~* 'POST|GET|PUT|DELETE|MKCOL|COPY|MOVE') {
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, MKCOL, COPY, MOVE';
  add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

下面是一个更简单的例子:

server {
  listen        80;
  server_name   api.test.com;

  location / {

    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
      return 200;
    }

    ....
    # Handle request
    ....
  }
}
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐