码迷,mamicode.com
首页 > 其他好文 > 详细

Nginx 跨域配置

时间:2017-08-01 23:08:25      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:man   max   参考   browser   pos   rest   问题   with   add   

随着 RESTFul 的流行,就会牵扯到跨域问题,那么小伙伴有没有被坑过,高人绕过,有需求的请往下看:

location / {
  if ($request_method = ‘OPTIONS‘) {
    add_header ‘Access-Control-Allow-Origin‘ ‘*‘;
    #
    # Om nom nom cookies
    #
    add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
    add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
    #
    # 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‘) {
    add_header ‘Access-Control-Allow-Origin‘ ‘*‘;
    add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
    add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
    add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘;
  }
  if ($request_method = ‘GET‘) {
    add_header ‘Access-Control-Allow-Origin‘ ‘*‘;
    add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
    add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
    add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘;
  }
}

大家看这代码是否有点臃肿?那么这样呢?

location / {
  add_header ‘Access-Control-Allow-Origin‘ ‘*‘;
  add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
  add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, PUT, DELETE, OPTIONS‘;
  add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Token‘;
  if ($request_method = ‘OPTIONS‘) {
    add_header ‘Access-Control-Max-Age‘ 1728000;
    add_header ‘Content-Length‘ 0;

    return 204;
  }
}

依然可以达到跨域效果,但是有什么缺点,欢迎交流~

参考 :https://michielkalkman.com/snippets/nginx-cors-open-configuration/

Nginx 跨域配置

标签:man   max   参考   browser   pos   rest   问题   with   add   

原文地址:http://www.cnblogs.com/kuyuecs/p/7270784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!