Nginx关于跨域的配置

参考:https://www.cnblogs.com/sunmmi/articles/5956554.html

最终我们项目中的配置如下:

upstream boss_gateway {
   server 127.0.0.1:32100 max_fails=2 fail_timeout=3s;
}

server {
    server_tag off;
    server_info off;
    server_tokens off;

    listen       80;
    server_name boss.域名.com;

    #access_log  /data/nginx-logs/boss-access.log  log_json;
    error_log  /data/nginx-logs/boss-error.log;

    set $cors '';
    if ($http_origin ~* 'https?://(localhost|crm*\.域名\.com|scm*\.域名\.com|testecm\.域名\.com|erp*\.域名\.com|bi*\.域名\.com)') {
        set $cors 'true';
    }

    set $corflag 0;
    if ($cors = 'true') {
        set $corflag "${corflag}1";        
    }
    if ($request_method = OPTIONS) {
        set $corflag "${corflag}2";        
    }

    location ^~ /api {
        if ($cors = 'true') {
            add_header 'Access-Control-Allow-Origin' "$http_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,Access-Token,RESPONSE-TYPE,responseType,GSID';
        }
        if ($corflag = "012") {
            add_header 'Access-Control-Allow-Origin' "$http_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,Access-Token,RESPONSE-TYPE,responseType,GSID';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
         }
        proxy_pass http://boss_gateway/;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-Ip $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

 

posted @ 2018-06-26 19:06  自行车上的程序员  阅读(2214)  评论(0编辑  收藏  举报