Nginx:如果标头不存在或错误,则拒绝请求 [英] Nginx: Reject request if header is not present or wrong

查看:42
本文介绍了Nginx:如果标头不存在或错误,则拒绝请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have the headers: X_HEADER1 & X_HEADER2, I want to reject all requests if either of these headers are not set or do not contain the correct values. What is the best way to do this?

谢谢

推荐答案

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

You can use two IF statements either before or in the location block to inspect the headers and then return a 403 error code if it is present. Alternatively, you can use those IF statements to rewrite to a specific location block and deny all in that location:

if ($http_x_custom_header) {
    return 403;
}

参考:
https://www.nginx.com/resources/wiki/start/主题/深度/ifisevil/
https://nginx.org/en/docs/http/ngx_http_access_module.html

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

Adding more detail per comment/request:

if ($http_x_custom_header) {
    return 405;
}

这会检查标题是否存在

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

if you want to check to see if the correct values exist, then you first need to map the correct values to a variable.

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

if ($is_ok) {
    return 405; 
}

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

删除了映射块后的分号,因为这会导致错误.

Removed semicolon after map block since this causes an error.

这篇关于Nginx:如果标头不存在或错误,则拒绝请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆