如何解决Nginx有条件地允许所有人响应基于IP的子路由
我正在设置NGINX服务器,需要对其进行配置,以仅允许某些IP访问React应用程序的根,但允许全部访问某个子文件夹(反应路由)。基本上,我需要允许所有流向/ sub /的流量,但只允许少数几个IP到达主目录/。 我尝试过
location /sub/* { allow all;}
location / {
allow x.x.x.x;
deny all;}
,但使用除“ x.x.x.x”以外的任何其他IP地址时,出现403错误。 实现此目的的正确方法是什么?
谢谢。
解决方法
这是您可以尝试做的事情:
map $uri $disallow_by_route {
~^/subroute/ ""; # allow /subroute/... for all
default 1;
}
map $remote_addr $disallow {
x.x.x.x ""; # some allowed IP
y.y.y.y ""; # another allowed IP
default $disallow_by_route;
}
server {
...
location / {
if ($disallow) { return 403; }
...
}
}
但是,如果允许的页面使用了/subroute/...
以外的其他路径中的某些资产(js,css,图像等),则此配置将不允许它们在受限IP上加载。您可以尝试让他们使用更复杂的Referer
区块链来检查HTTP map
标头的值:
map $http_referer $disallow_by_referer {
# use a regex for your actual domain here
~^https?://example\.com/subroute/ "";
default 1;
}
map $uri $disallow_by_route {
~^/subroute/ "";
# list all the other possible assets extensions (png,gif,svg,webp etc.) here
~\.(?:js|css)$ $disallow_by_referer;
default 1;
}
map $remote_addr $disallow {
x.x.x.x ""; # some allowed IP
y.y.y.y ""; # another allowed IP
default $disallow_by_route;
}
server {
...
location / {
if ($disallow) { return 403; }
...
}
}
请注意,如果您的服务器配置(或响应应用本身)将引荐策略设置为no-referer
,则此解决方案将不起作用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。