首页 > 解决方案 > Nginx有条件地允许所有人根据IP响应子路由

问题描述

我正在设置 NGINX 服务器,需要将其配置为仅允许某些 IP 访问反应应用程序的根目录,但允许所有 IP 访问某个子文件夹(反应路由)。基本上我需要允许所有流量到 /sub/,但只允许少数 IP 到主目录 /。我试过

    location /sub/* { allow all;}
        
location / {
    allow x.x.x.x;
    deny all;}

但在使用除“xxxx”之外的任何其他 IP 地址时出现 403 错误。实现这一目标的正确方法是什么?

谢谢。

标签: nginxnginx-confignginx-location

解决方案


以下是您可以尝试执行的操作:

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.


推荐阅读