• Nginx解决跨域问题(CORS)


    跨域

    解决跨域问题一般有两种思路:

    CORS
    在后端服务器设置 HTTP 响应头,把你需要运行访问的域名加入加入 Access-Control-Allow-Origin中。

    jsonp
    把后端根据请求,构造 json 数据,并返回,前端用 jsonp 跨域。

    这两种思路,本文不展开讨论。

    需要说明的是,nginx 根据第一种思路,也提供了一种解决跨域的解决方案。

    环境

    centos7
    nginx:latest

    如何配置

    编写 enable-cors.conf

    参考如下

    # allow origin list
    set $ACAO '*';
    
    # set single origin
    if ($http_origin ~* (www.helloworld.com)$) {
      set $ACAO $http_origin;
    }
    
    if ($cors = "trueget") {
        add_header 'Access-Control-Allow-Origin' "$http_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-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }
    
    if ($request_method = 'OPTIONS') {
      set $cors "${cors}options";
    }
    
    if ($request_method = 'GET') {
      set $cors "${cors}get";
    }
    
    if ($request_method = 'POST') {
      set $cors "${cors}post";
    }
    

    引入配置

    # ----------------------------------------------------
    # 此文件为项目 nginx 配置片段
    # 可以直接在 nginx config 中 include(推荐)
    # 或者 copy 到现有 nginx 中,自行配置
    # www.helloworld.com 域名需配合 dns hosts 进行配置
    # 其中,api 开启了 cors,需配合本目录下另一份配置文件
    # ---------------------------------------------------
    server {
      listen       80;
      server_name  *****.com;
    
      location ~ ^/api/ {
        include enable-cors.conf;   ####关键语句
        proxy_pass http://api_server;
        rewrite "^/api/(.*)$" /$1 break;
      }
    
      location ~ ^/ {
        proxy_pass http://front_server;
      }
    }
    

    针对如何解决跨域,方案有很多,本文只是提供了一种思路,方便学习参考
    参考文章

  • 相关阅读:
    Python 模拟SQL对文件进行增删改查
    Python用户登陆
    计算程序的内存和占比
    列出top中的pid
    编写类du命令Python脚本
    生成器版本的文件MD5校验
    利用os、hash模块生成目录下所有文件的md5
    文件Copy和文件夹Copy
    Access数据库连接方式
    js常用方法收集
  • 原文地址:https://www.cnblogs.com/ovim/p/13193389.html
Copyright © 2020-2023  润新知