限制 Blob 中 IP 使用 nginx 和 Gunicorn 访问管理员 URL



我试图通过在nginx中使用简单的基于主机的访问控制来限制对我的django应用程序的管理员部分的访问。不幸的是,nginx似乎不遵守配置请求:

这是我在nginx中对这个特定部分的设置:

# gunicorn setup
location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }

 location /admin/ { # restrict access to admin section
    allow 192.168.0.1;
    deny all;
 }

这仍然会阻止我的 ip 192.168.0.1。我做错了什么?有没有另一种方法可以阻止访问 django 应用程序的/admin/部分?

我通过将/admin/位置替换为以下内容找到了解决此问题的方法:

location ^~ /admin/ { # restrict access to admin section
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    allow 192.168.0.1;
    deny all;
}

我希望这将节省某人在互联网上的一些长时间搜索。我将不胜感激提供更好的解决方案的答案。

如果您使用的是 AWS 负载均衡器
然后,您将遇到一个问题,即传递的IP不是客户端IP,而是LB的IP。

您将需要在此处使用不同的阻止机制。请精确地执行以下操作。

将以下内容添加到顶级http块:

    # The X-Forwarded-For is the client IP which is what we need insted of the
# load balancer IP
real_ip_header X-Forwarded-For;
set_real_ip_from 10.0.0.0/8;
log_format main '$remote_addr - $remote_user $time_local '
                '"$request" $status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"' ;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

将以下内容添加到server。 将该x.x.x.x替换为您的 VPN 或列入白名单的 IP。例如:?44.231.29.79?$

# Only allow access to admin panel through VPN IP
location ^~ /admin/ { # restrict access to admin section
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    set $allow false;
    if ($http_x_forwarded_for ~ " ?x.x.x.x?$") {
        set $allow true;
    }
    if ($http_x_forward_for ~ " ?x.x.x.x$") {
        set $allow false;
    }
    if ($allow = false) {
        return 403;
    }
}  

答案摘自 AWS 论坛 https://forums.aws.amazon.com/thread.jspa?threadID=62474#

最新更新