【问题标题】:Nginx X-Accel-Redirect not working with node.jsNginx X-Accel-Redirect 不适用于 node.js
【发布时间】:2023-03-04 23:41:01
【问题描述】:

我正在尝试在由 node.js 支持的 nginx 上设置授权文件访问。出于某种原因,所有示例都不适合我。我正在尝试从/data/private/files 提供文件服务

我的 nginx 配置:

...
server {
    listen 4000;
    server_name localhost;

    location / {
        proxy_pass http://127.0.0.1:3000/;
    }

    location /files {
        root /data/private;
        internal;
}  

我的节点 server.js:

var http = require('http');
http.createServer(function (req, res) {
  console.log(req.url);
  res.end('works');
}).listen(3000);

当我请求http://localhost:4000/xyz 时,请求被正确传递到节点。当我请求http://localhost:4000/files/test.jpg 时,我只得到一个 404 并且没有任何东西传递给节点。我究竟做错了什么?当我推荐 internal 然后 test.jpg 直接由 nginx 正确提供,所以我假设路径是正确的?

我很确定我之前在某个时候有过这个工作,但是在某个不同的服务器上可能有不同的节点和 nginx 版本。尝试使用 nginx 1.6.0 和 1.2.6,节点 v0.10.21。我还添加了您在所有示例中找到的所有 proxy_set_header 和 proxy_pass 选项,但没有任何效果。我现在正在基于 Vagrant 的 Ubuntu VM 中运行它,但也不能在 Mac 上运行。

我知道我必须通过res.setHeader("X-Accel-Redirect", req.url); 设置标头,但这不是这里的问题,因为我什至没有进入可以在节点中设置所需标头的阶段。

【问题讨论】:

    标签: node.js nginx x-accel-redirect


    【解决方案1】:

    您误解了 internalX-Accel-Redirect 的工作原理。

    主要思想是您转到某个代理到应用程序的 URL。然后应用程序决定您是否应该访问文件。在前一种情况下,它以X-Accel-Redirect 响应受保护的网址(一个以internal 响应)。

    所以你应该去一些其他的网址,例如http://localhost:4000/get/files/test.jpg,您的应用程序可能如下所示:

    var http = require('http');
    http.createServer(function (req, res) {
      if (req.url.indexOf('/get/files/') == 0) {
        if (userHasRightToAccess()) {
          res.setHeader('X-Accel-Redirect', res.url.slice(4));
          res.end('');
        } else {
          // return some error
        }
      } else {
        console.log(req.url);
        res.end('works');
      }
    }).listen(3000);
    

    【讨论】:

    • 非常感谢!完全有道理,我读得越多,我就不知何故迷路了。坚持请求和路径必须匹配的想法。花几个小时,再次感谢!
    • 嘿 Alexey,我在客户端 ajax 端使用它来访问 nginx 服务器在内部重定向返回的文件:http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { localStorage.setItem("Authorization",http.getResponseHeader("Authorization")); window.document.write(http.responseText); } 但它对我不起作用。我将页面 html 内容作为响应正文的一部分,但它正在当前选项卡中打开页面。你能帮忙吗?
    • @gonephishing nginx的内部重定向与ajax无关。创建新问题
    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2013-04-17
    相关资源
    最近更新 更多