【问题标题】:Serve Express.JS app from subfolder从子文件夹服务 Express.JS 应用程序
【发布时间】:2021-06-20 05:31:25
【问题描述】:

我使用 nginx 在同一域下提供静态 html 站点和 expressjs 应用程序。我的 nginx 配置如下所示:

    location / {
            try_files $uri $uri/ /index.html;
            autoindex  off;
            root /var/www/example.com/static/;
    }

    location /admin {
            proxy_pass http://localhost:3007/;
            proxy_set_header Host $host;
            proxy_buffering off;
            autoindex  off;
    }

如果我访问 example.com/admin,我可以访问在端口 3007 上运行的应用程序,因此我的 app.get('/', routes.index); 似乎正在运行,但我在其他路线上运行时遇到了一些麻烦。

例如:

app.get('/admin/test', function(req, res) {
    console.log("test!")
});

如果我尝试访问example.com/admin/test,根据我的日志,我只会看到Cannot GET //test 和404:

GET //test 404 11ms

如果我将路由更改为 /test,则会出现同样的问题。任何指针那里有什么问题。我还没有找到一种方法来使路由相对于它们安装到的基本路径 (/admin)。

谢谢!

【问题讨论】:

    标签: node.js nginx express


    【解决方案1】:

    注意斜线:

    location /admin {
        proxy_pass http://localhost:3007/; # here
        …
    }
    

    如果你删除它,真正的请求 URI 将被代理。

    您还可以使用 Nginx 删除 /admin 部分:

    location ~ ^/admin($|/.*$) {
        proxy_pass http://localhost:3007$1;
        …
    }
    

    【讨论】:

    • 有时最重要的是小事。删除斜线做了轨道。感谢您的快速(几乎太快了,我必须等待几分钟才能接受它;))回复!
    • 不能写成/admin/? 做同样的事情吗?我想做同样的事情,想知道这是否也能奏效。
    • @Bill:($|/.*$) 与其说是允许可选的/(我认为 Nginx 无论如何都会这样做)不如捕获/admin 之后的路径部分,所以它可以给proxy_pass(见最后的$1)。 proxy_pass http://localhost:3007 将导致 /admin 也被传递。
    • 哦,好的。谢谢你的澄清。我也很欣赏对这个非常古老的问题的快速回复。
    【解决方案2】:

    您仍然可以使用“/”(正斜杠)保留您的 Nginx 配置代码,并使用 example.com/admin/test 访问测试路由。

    app.get('//test', function(req, res) {
        console.log("test!")
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 2013-03-28
      • 1970-01-01
      相关资源
      最近更新 更多