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

查看:388
本文介绍了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?

谢谢

推荐答案

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

Reference:
https://www.nginx.com/resources/wiki/start/topics/depth/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天全站免登陆