Nginx根据Origin配置禁止跨域访问策略

产品需要通过某所的安全测评扫描,其中提出一个关于跨域策略配置不当的问题,如下:

 

 

 

这个需要根据客户端传递的请求头中的Origin值,进行安全的跨站策略配置,目的是对非法的origin直接返回403错误页面,配置如下:

1、在http中定义一个通过map指令,定义跨域规则并返回是否合法

map $http_origin $allow_cors {
"~^(https?://(dmp.xxxxxx.cn)?)$" 1; "~^\s" 1; "~*" 0; }

上述规则中,如果orgin的值为https://dmp.xxxxxx.cn或者空字符串,我们认为是合法的请求,返回数值1,如果是其它值,返回数值0

 

2、在server中根据$allow_cors的值进行请求拦截

if ($allow_cors = 0){
     return 403;
}

 

完整配置参考:

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    map $http_origin $allow_cors {
        "~^(http?://(dmp.xxxxxx.cn)?)$" 1;
        "~^\s" 1;
        "~*" 0;
    }

    server {
        listen       80;
        server_name  localhost;

        if ($allow_cors = 0){
             return 403;
        }

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
           proxy_pass http://192.168.10.105;
        }

    }

}

 

最终效果:

 

 

 

 

 

 

 

posted @ 2022-04-20 10:39  codest  阅读(3292)  评论(0编辑  收藏  举报