nginx - Nginx有条件地允许所有人根据IP响应子路由
问题描述
我正在设置 NGINX 服务器,需要将其配置为仅允许某些 IP 访问反应应用程序的根目录,但允许所有 IP 访问某个子文件夹(反应路由)。基本上我需要允许所有流量到 /sub/,但只允许少数 IP 到主目录 /。我试过
location /sub/* { allow all;}
location / {
allow x.x.x.x;
deny all;}
但在使用除“xxxx”之外的任何其他 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
使用更复杂的map
块链检查 HTTP 标头的值:
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
.
推荐阅读
- python - 为什么 x 和 y 的 id() 相同,而 list_1 和 list_2 却不同?
- python - 如何使用 OOP 在 Tkinter 中调用特定屏幕
- google-earth-engine - 重新分类图像集合中所有图像中的所有像素值 - GEE
- chisel - Chisel3 REPL Vec 分配到模块仅在评估后有效
- vba - 表格计数复制到excel中
- javascript - 如何在javascript中读取在线文件作为变量
- jupyter-notebook - 如何在 Google Colab 中做内部链接
- python - 从 Python 中的 API 请求中提取数据
- javascript - 当我将它们添加到包含数组时,如何确保 js 数组尊重元素顺序?
- javascript - React/NextJS - 音频播放器