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

Pau*_*aul 47 nginx

如果我有标题:X_HEADER1和X_HEADER2,我想拒绝所有请求,如果这些标题中的任何一个未设置或不包含正确的值.做这个的最好方式是什么?

谢谢

小智 53

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

if ($http_x_custom_header) {
    return 403;
}
Run Code Online (Sandbox Code Playgroud)

参考:
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;
}
Run Code Online (Sandbox Code Playgroud)

这看起来是否存在标头

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

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

if ($is_ok) {
    return 405; 
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 链接似乎已过时.这些似乎是更新的替代品.https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/ http://nginx.org/en/docs/http/ngx_http_access_module.html (4认同)
  • +1,如果你能提供一些例子,那将会更受欢迎,:). (2认同)

Âng*_*tto 19

我研究了很多来解决一个简单的问题:如果请求在标头中有特定的令牌,则只允许 proxy_pass。我在这里尝试了所有答案,但没有任何效果我喜欢。我的最终解决方案是:

location /api {
    proxy_http_version 1.1;

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

    proxy_pass http://app:3000/;
}
Run Code Online (Sandbox Code Playgroud)

参考:

NGINX 不等于

nginx - 从上游服务器读取自定义标头

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

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