• 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/

  • 相关阅读:
    ISO/IEC 9899:2011 条款6.10.3——宏替换
    ISO/IEC 9899:2011 条款6.10.2——源文件包含
    关于Objective-C新增的__kindof关键字
    ISO/IEC 9899:2011 条款6.10.1——条件包含
    ISO/IEC 9899:2011 条款6.10——预处理指示符
    ISO/IEC 9899:2011 条款6.9.2——外部对象定义
    Objective-C中使用不定参数个数的方法调用
    php添加数据到xml文件的例子
    nginx rewrite重写与防盗链配置
    nginx url自动加斜杠的问题
  • 原文地址:https://www.cnblogs.com/kuyuecs/p/7270784.html
Copyright © 2020-2023  润新知