【问题标题】:Nginx: Reject request if header is not present or wrongNginx:如果标头不存在或错误,则拒绝请求
【发布时间】:2013-09-29 00:29:30
【问题描述】:

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

谢谢

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您可以在位置块之前或中使用两个 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; 
    }
    

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

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

    【讨论】:

    【解决方案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/

    【讨论】:

      【解决方案3】:

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

      以下示例仅允许访问 header1 值为“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
          ';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-30
        • 2019-01-18
        • 2016-01-13
        • 1970-01-01
        • 2018-09-19
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        相关资源
        最近更新 更多