美文网首页
Nginx解决跨域配置(Cors),支持白名单

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

作者: 冰鱼飞鸟 | 来源:发表于2018-06-02 23:39 被阅读0次
server {
        listen 8082;
        server_name localhost;

        location /test{
            proxy_pass http://proxyedservice:8001/;
            set $cors '';
            #$http_origin 获取http请求中header中的origin值
            if ( $http_origin ~* 'http://(localhost|127\.0\.0\.1).*') {     
                #通过正则表达式设置白名单,通过白名单的则允许跨域       
                set $cors 'true';
            }
            if ( $cors = 'true') {
                add_header 'Access-Control-Allow-Origin' "$http_origin ";
                add_header 'Access-Control-Allow-Credentials' 'true';
                #为预检请求加的header
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                #为预检请求加的header
                add_header 'Access-Control-Allow-Headers'
                 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
            }
            #支持请求(带预检的跨域请求)的预检请求
            if ( $request_method = 'OPTIONS') {
                return 204;
            }
        }
    }  

说明:

  1. location /test 与proxy_pass proxy_pass http://proxyedservice:8001/

会把如 :http://localhost:8082/test/**** 转发给http://proxyedservice:8001/*****
相当于把/test及其前面那一截替换成proxy_pass,后面那一截照发。

2.$http_origin
并不是nginx的内置参数,nginx支持取自定义的参数值,$http_XXX这个格式是nginx取请求中header的XXX的值的。这里取的是origin,而一般跨域请求都会将请求的来源放在origin中(浏览器会往跨域请求的header上面加origin这个header)。

3.白名单可以通过正则表达式来配置。

如: if ( $http_origin ~* 'http://(localhost|127.0.0.1).*')

4.跨域资源共享 CORS 详解

相关文章

网友评论

      本文标题:Nginx解决跨域配置(Cors),支持白名单

      本文链接:https://www.haomeiwen.com/subject/dkhrsftx.html