Nginx配置origin限制跨域请求(应对等保)

Nginx需要修复一个安全漏洞

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

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

http {
    
    
    ...
    # 说明:一般使用http_origin来进行跨域控制,当不传递origin头的时候,就为这个里面的默认值,当传递有值得时候,才会走下面得正则匹配
    map $http_origin $allow_cors {
    
    
        default 1;
        "~^https?://.*?\.theorydance\.com.*$" 1;
        "~^(https?://(dmp.xxxxxx.cn)?)$" 1;
        "~*" 0;
    }
    server {
    
    
        location / {
    
    
            if ($allow_cors = 0){
    
    
                return 403;
            }
            root /data/deploy;
        }
    }
}

上述规则中,
a.当不传递origin头的时候,就为这个里面的默认值为1,
b.如果orgin的值为https://dmp.xxxxxx.cn或者含“theorydance”的,我们认为是合法的请求,返回数值1,如果是其它值,返回数值0

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

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

3、在server中添加头部

#指定允许其他域名访问        
add_header Access-Control-Allow-Origin $http_origin;
#允许的请求类型
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
#许的请求头字段
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";

验证
1.不指定 origin时,请求正常
在这里插入图片描述

2.指定合法 origin时,请求正常
在这里插入图片描述
3.指定非法origin时,请求返回403
在这里插入图片描述
参考链接
https://www.cnblogs.com/justtosee/p/16987894.html
https://www.cnblogs.com/TheoryDance/p/16277577.html

猜你喜欢

转载自blog.csdn.net/qq_20236937/article/details/128640137
今日推荐