【问题标题】:Nginx Restrict Access to FileNginx 限制对文件的访问
【发布时间】:2020-07-07 04:20:59
【问题描述】:

目前我的配置文件(/etc/nginx/sites-available/default)说

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location /credentials.js {
                deny all;
                return 404;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

}

但我仍然可以通过 web 上的 example.com/credentials.js 访问 credentials.js。有什么建议么?

【问题讨论】:

  • 关于您可以访问的网址以及配置的其余部分是什么?
  • 我已经用你的问题的答案更新了我的问题。
  • 你能把整个/credential.js块移到location /里面吗?再试一次
  • 这并没有解决问题。结果相同。
  • 运行nginx -T 并输出到您的问题

标签: ubuntu nginx


【解决方案1】:

尝试将= 添加到您的位置,这将完全匹配:

server {
    server_name _;
    listen 80 default_server;

    location = /credentials.js {
        deny all;
        return 404;
    }

    location / {
        add_header Content-Type text/plain;
        return 200 "hello world\n\n";
    }
}

来自nginx location docs:

如果找到完全匹配,则搜索终止。例如,如果“/”请求频繁发生,定义“location = /”将加速这些请求的处理,因为搜索在第一次比较后立即终止。这样的位置显然不能包含嵌套的位置。

【讨论】:

  • @SamastVarma 尝试答案中的小例子,如果需要,只需更改 server_name/port。
  • 'Still not working',你是不是忘记更改后重新加载nginx配置? location = /credentials.jslocation ~* credentials.js 应该拒绝对文件的访问。
  • 昨晚我用= 更新了我的代码并重新加载,但仍然能够从网络访问该文件。我今天早上又试了一次,它正确地返回了 404。谢谢!
猜你喜欢
  • 2012-04-06
  • 2014-04-24
  • 2019-03-08
  • 2013-01-04
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多