Nginx:如果标头不存在或错误,则拒绝请求

时间:2013-09-23 23:37:45

标签: nginx

如果我有标题:X_HEADER1& X_HEADER2,如果未设置其中任何一个标头或者不包含正确的值,我想拒绝所有请求。这样做的最佳方式是什么?

由于

3 个答案:

答案 0 :(得分:46)

您可以在位置块之前或位置块中使用两个IF语句来检查标头,然后返回403错误代码(如果存在)。或者,您可以使用这些IF语句重写到特定的位置块并拒绝该位置中的所有内容:

if ($http_x_custom_header) {
    return 403;
}

参考:
https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
https://nginx.org/en/docs/http/ngx_http_access_module.html

为每条评论/请求添加更多详细信息:

if ($http_x_custom_header) {
    return 405;
}

这会查看标头是否存在

如果要检查是否存在正确的值,则首先需要将正确的值映射到变量。

map $http_x_header $is_ok {
    default "0";
    Value1  "1";
    Value2  "1";
    Value3  "1";
}

if ($is_ok) {
    return 405; 
}

首先将标题值映射到是否正常,然后检查变量是否正常。

编辑:在地图块后删除了分号,因为这会导致错误。

答案 1 :(得分:2)

为了解决一个简单的问题,我做了很多研究:仅在请求的标头中有特定令牌的情况下才允许proxy_pass。我在这里尝试了所有答案,但是没有什么能像我喜欢的那样工作。我的最终解决方案是:

location /api {
    proxy_http_version 1.1;

    if ($http_authorization != "Bearer 1234") {
        return 401;
    }

    proxy_pass http://app:3000/;
}

参考:

NGINX not equal to

nginx - read custom header from upstream server

https://serverfault.com/questions/490760/nginx-location-exact-match-matches-beyond-arguement

https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

答案 2 :(得分:1)

如果只允许基于响应标头中放置的某些有效标头值来允许HTTP请求,则一种可能的方法是使用OpenResty工具施加此类限制。

以下示例仅允许访问标头1的值为“ name1”或“ name2”的请求:

    header_filter_by_lua '
    local val = ngx.header["header1"]
    if val then
            if (val ~= "name1") and (val ~= "name2") then
                return ngx.exit(400)
            end
    end
    ';
相关问题