【问题标题】:Nginx :allow folder access only from localhostNginx :只允许从本地主机访问文件夹
【发布时间】:2019-07-07 00:40:18
【问题描述】:

我有一个名为admin 的文件夹,它位于var/www/html 目录中。

我想从公共 Internet 访问该文件夹,即只允许从 localhost 访问。

为此

1) 在sites-available目录下创建了一个文件whitelist-admin,并添加了以下内容。

server{

location ~ /admin/.*\.php$ {
     allow 127.0.0.1;
     try_files $uri $uri/ /index.php;
     deny all;
  }

}

当我访问 <public-ip>/admin 时,我收到 403 错误,但链接 <public-ip>/admin/index.php 正在工作,我想禁用它。

【问题讨论】:

  • 是否有需要从公共域访问的链接?
  • 我只想完全禁止从公共互联网访问admin 文件夹(只允许本地主机访问)
  • 那么位置就不行了~ ^/admin { #what you have there} 工作吗?我的意思是,在任何包含 /admin 的链接中只允许 127.0.0.1,不管它是否以 .php 结尾
  • 那么我该如何正确禁用访问权限

标签: php .htaccess ubuntu nginx


【解决方案1】:
server {

    location = /admin { # its good to block the admin alone too
        allow 127.0.0.1;
        deny all;
        try_files $uri $uri/ /index.php;
    }

    location ^~ /admin/ { # block anything beginning with /admin/
        allow 127.0.0.1;
        deny all;
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf; 
        #fastcgi_index index.php; 
        # With php7.0-cgi alone: 
        #fastcgi_pass 127.0.0.1:9000;
        # With php7.0-fpm: fastcgi_pass unix:/run/php/php7.0-fpm.sock; 
    }

}

此配置应仅允许本地主机连接,并拒绝任何管理 url 上的所有其他连接。

另一方面,如果您的计算机被阻止,可能是因为您是通过公共 ip 而不是直接通过 localhost 发出请求。(例如:如果您通过互联网进行重定向,您的 ip 将是服务器 ip,而不是本地主机)。

这应该可以解决问题,如果没有,也许有另一个位置可以捕获连接,而不是这个。评论它是否有效或无效。

编辑:

了解它的来源:https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms

^~ 表示这是配置中最好的“~”,它将是在“=”位置之后的第一个被检查的。这应该优先于您的 /admin/ 位置而不是 .php 位置。

这应该有效。 (最后:D)

【讨论】:

  • 它不工作我可以访问admin/index.php
  • 很奇怪,因为它不应该,应该是与 try_files 的罕见交互。尝试测试,将 try_files 更改为“return 302 www.google.com;”并尝试使用外部 IP 进行重定向。如果您从外部 IP 重定向,我将打开我的测试平台并尝试重现您的问题并找到解决方案。
  • 奇怪的是它没有重定向我得到相同的结果我认为配置不起作用
  • 那么有两种可能。 1,尝试文件正在做奇怪的事情,需要更专业的解决方案或 2,还有另一个位置块,可能是在进入此管理位置块之前捕获 .php 的东西,它允许外部连接。有没有其他可以捕获 .php 或 index * 的配置?
  • 让我再检查一下配置
猜你喜欢
  • 2017-09-11
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多