【问题标题】:How to restrict ip access in nginxnginx限制ip访问的方法
【发布时间】:2020-04-11 04:48:58
【问题描述】:

我想通过 IP 限制 Nginx reverse_proxy 中特定 php 文件的访问。 所以在我的虚拟主机路径/etc/nginx/sites-available/sub.mydmn.com 我有以下配置:

server {
    server_name wwww.sub.mydmn.com sub.mydmn.com;
    root /home/mydmn/;

    access_log off;

    # Static contents
    location ~* ^.+.(png|mp4|jpeg)$ {
        expires max;
    }

    # Limit IP access
    location = /mine.php {
        allow <MyIP_Here>;
        deny all;
        return 404;
    }

    # Dynamic content, forward to Apache
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8080;
    }
}

# Deny server with IP access!
server {
    listen 80 default_server;
    server_name _;
    location / {
    return 403;
    }
}

但是当我启动服务器时,Nginx 会阻止 mine.php 的所有 IP。 有什么问题?

【问题讨论】:

  • @RogertheShrubber 我不需要白名单,我想只允许在 reverse_proxy 中使用 1 个 IP 地址访问 mine.php,
  • 您应该将 return 404 替换为来自另一个 location 块的四个 proxy_ 语句。
  • @Richard Smith 非常感谢。您能否创建完整的答案以使我更清楚?

标签: nginx reverse-proxy


【解决方案1】:

Nginx 选择单个location 块来处理请求(参见this document)。您的 location = /mine.php 块,不仅如果 IP 地址被拒绝返回 403 状态,而且如果 IP 地址被允许返回 404 状态。如果 IP 地址允许,则需要由 8080 端口上的服务处理请求。

一种解决方案是复制 location / 块中的语句。

例如:

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;

location = /mine.php {
    allow ...;
    deny all;
    proxy_pass http://127.0.0.1:8080;
}
location / {
    proxy_pass http://127.0.0.1:8080;
}

请注意,proxy_set_header 语句可以移动到外部块中,以便它们被两个块继承。详情请见this document。

【讨论】:

  • 太棒了!!,太完美了
猜你喜欢
  • 2015-11-30
  • 2022-11-02
  • 2021-12-16
  • 2010-09-30
  • 1970-01-01
  • 2014-04-24
  • 2015-10-21
  • 1970-01-01
  • 2017-05-08
相关资源
最近更新 更多