zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    直接插入排序
    安卓突击:隐式、显式Intent
    安卓突击:Android 动画有哪几种?
    安卓突击:ANR
    安卓突击:系统上安装了多种浏览器,能否指定某浏览器访问指定页面
    安卓突击:系统上安装了多种浏览器,能否指定某浏览器访问指定页面
    Android:BroadcastReceiver的基础知识
    安卓突击:service的基础知识
    安卓突击:数据存储方式
    Android突击:常用的五种布局
  • 原文地址:https://www.cnblogs.com/kuyuecs/p/7270784.html
Copyright © 2011-2022 走看看