Nginx有条件地允许所有基于IP的反应子路由

Nginx conditionally allow all to react sub-route based on IP

我正在设置 NGINX 服务器,需要将其配置为仅允许特定 IP 访问 React 应用程序的根目录,但允许所有 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。您可以尝试让他们使用更复杂的 map 区块链检查 HTTP Referer header 的值:

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; }
        ...
    }
}

请注意,如果您的服务器配置(或 React 应用程序本身)将引用策略设置为 no-referer,则此解决方案将不起作用。