【问题标题】:Nginx doesnot redirect to Node (localhost://3000) instead serves the default webpage?Nginx 不会重定向到 Node (localhost://3000) 而是提供默认网页?
【发布时间】:2021-05-23 16:08:11
【问题描述】:

我似乎无法弄清楚我在这个简单的设置中做错了什么,所以我设置了一个节点应用程序(测试起来超级简单),如下所示:

// import express
const express = require('express');

// create new express app and assign it to `app` constant
const app = express();

// server port configuration
const PORT = 3000;

// create a route for the app
app.get('/', (req, res) => {
  res.send('Hello this seems to work!');
});

// server starts listening the `PORT`
app.listen(PORT, () => {
  console.log(`Server running at: http://localhost:${PORT}/`);
});

我的 nginx 服务器配置看起来像这样

server {
    listen 80;
    server_name  www.example.org;

    #add in ssh details here later

    #These lines create a bypass for certain pathnames
    #www.example.com/test.js is now routed to port 3000
    #instead of port 80
    location ~* \.(js)$ {
        proxy_pass http://localhost:3000;
        # proxy_set_header Host $host;
    }
}

现在根据我的说法,当我运行它时 - nginx 应该重定向以表示总是是的?但是当我访问该网站时,我一直看到欢迎使用 nginx 页面 - 而不是“你好,这似乎有效!”

我关注了这个页面,因为它有类似的静态文件案例,比如我 Express + Nginx. Can't serve static files

【问题讨论】:

    标签: node.js nginx


    【解决方案1】:

    当你查看 nginx 的配置时

     location ~* \.(js)$ {
            proxy_pass http://localhost:3000;
            # proxy_set_header Host $host;
        }
    

    Nginx 仅将以“.js”结尾的请求转发到您的 express 应用程序。访问http://localhost 主页的请求尚未被此块处理,并且您拥有 nginx 默认页面(我认为在您的配置中某处有一个块可以提供静态文件)

    如果您想将所有请求转发到 Express 应用程序,您可以尝试:

     location / {
            proxy_pass http://localhost:3000;
            # proxy_set_header Host $host;
        }
    

    您可以在link 中找到正则表达式在 Nginx 中的工作原理

    【讨论】:

    • 我也想通了!感谢您的帮助
    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 2018-08-07
    • 2017-07-18
    • 2014-10-22
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    相关资源
    最近更新 更多