Nginx 跨域配置

Posted 流金岁月

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nginx 跨域配置相关的知识,希望对你有一定的参考价值。

随着 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 跨域配置的主要内容,如果未能解决你的问题,请参考以下文章

nginx配置反向代理解决vue跨域问题

Nginx解决跨域配置(Cors),支持白名单

nginx 跨域配置

宝塔面板Nginx反向代理解决跨域问题

Nginx配置springboot-vue跨域

nginx 解决跨域、手机测试 2019-05-27