【问题标题】:Nginx location to restrict by IP returning 404Nginx 位置通过 IP 限制返回 404
【发布时间】:2016-02-24 20:41:52
【问题描述】:

我有一个文件和一个目录,都位于文档根目录内,我需要根据请求的 IP 地址限制对它们的访问。这是我设置的location 配置(实际路径和 IP 交换为示例):

server {
    server_name example.com;

    location ~* /(file.php|directory) {
        allow 1.1.1.10;
        allow 2.2.2.11;
        deny all;
    }
}

我的 Nginx 实例位于 CloudFlare 后面,因此我在 Nginx 配置的 http 块中设置了以下规则:

set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 199.27.128.0/21;

real_ip_header CF-Connecting-IP;

我的访问日志显示 IP 地址已根据该配置正确设置。

Nginx 实例被用作负载平衡器,将请求传递给上游的一组 Apache 服务器。该上游工作正常,使用以下location 配置:

location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;
        proxy_set_header CF-Ipcountry $http_cf_ipcountry;
        proxy_set_header CF-Ray $http_cf_ray;
        proxy_set_header Cf-Visitor $http_cf_visitor;

        proxy_pass http://web;
}

我的 IP 限制 location 规则高于配置文件中的 location / 规则。

问题出在:每当我从应该允许的 IP 和被阻止的 IP 向 IP 限制路径之一发出请求时,我都会收到 404 响应.请求 IP 不会影响此响应。

当从被阻止的 IP 请求时,我期待 403 响应。我已经在不同的server 上测试了相同的location 配置,它直接处理文件而不是将它们传递到上游,并且它按预期工作,即使在具有相同真实 IP 设置的 CloudFlare 之后也是如此。

我还需要做什么才能使此限制正常工作?

【问题讨论】:

  • 404 告诉你路径没有找到。当您在该位置块上添加自定义标头时会发生什么?它是否显示卷曲?您也必须将您的 proxy_pass 添加到该位置,因为它看起来不会去任何地方。

标签: apache nginx cloudflare


【解决方案1】:

问题是您误解了nginx 如何处理location 块。有关概述,请参阅 this document

您需要在每个需要执行该功能的location 块中放置一个proxy_pass 指令。 proxy_set_header 指令可以从外部块继承。例如:

server {
    server_name example.com;

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;
    proxy_set_header CF-Ipcountry $http_cf_ipcountry;
    proxy_set_header CF-Ray $http_cf_ray;
    proxy_set_header Cf-Visitor $http_cf_visitor;

    location ~* /(file.php|directory) {
        allow 1.1.1.10;
        allow 2.2.2.11;
        deny all;

        proxy_pass http://web;
    }

    location / {
        proxy_pass http://web;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-30
    • 2018-04-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2021-12-16
    相关资源
    最近更新 更多