【问题标题】:How to setup routes with Express and NGINX?如何使用 Express 和 NGINX 设置路由?
【发布时间】:2017-11-23 21:54:19
【问题描述】:

我正在尝试使用 NGINX 作为反向代理配置 Express 服务器。 NGINX 提供静态文件,Express 提供动态内容。

问题:正常的根链接有效(website.com),但是当我导航到(website.com/api)时,我从 NGINX 得到 404


这是我的 server.js:

var express = require("express");
var app = express();
var server = app.listen(process.env.PORT || 5000);

console.log("Server Running");

app.get("/",function(req,res){res.send("HOME PAGE")});

app.get("/api", function(req, res) {
    res.send('API PAGE');
});

这是我的 NGINX 配置文件:

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


    server_name website.com www.website.com;

    location ~ ^/(assets/|images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
    root /home/foobar/public; #this is where my static files reside
    access_log off;
    expires 24h;
    }

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect off;
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        try_files $uri $uri/ =404;
    }
}

【问题讨论】:

  • 您好,您能帮帮我吗,我正在尝试将我的 / 路由加载为我的主页,但 nginx 一直显示自己的主页。另外,当我尝试访问路由 /api 时,我不断收到 nginx 错误。这个proxy_pass http://localhost:5000; 有什么意义,而不是表明你的公共 ipv4 地址
  • @kd12345 你的节点 js 服务器应该在 localhost:5000 上运行,所以当 nginx 收到请求时,它会将其转发到 localhost:5000
  • 我的节点服务器不应该在端口 80 或 443 上运行?为什么我不在这里使用我的公共 IP 地址?
  • @kd12345 nginx 已经根据您的配置为您处理端口 80,433,您的服务器的 IP 访问直接是 nginx,请求通过 nginx 到达您的节点服务器。所以在 5000 上运行你的节点并使用 nginx 将请求传递给节点
  • 这样做后,即使我的本地计算机已关闭,我仍然可以从其他任何地方访问公共 IP 吗?我有完全相同的代码,但除了这个location ~ ^/(assets/|images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) { root /home/foobar/public; #this is where my static files reside access_log off; expires 24h; } 而不是location / { 这个location /api {

标签: node.js express nginx server digital-ocean


【解决方案1】:

尝试删除此行:

try_files $uri $uri/ =404;

使用这个指令,nginx 尝试提供静态文件(或目录),如果没有这样的文件,则返回 404

【讨论】:

  • 拯救了我的一天。非常感谢
  • 哦,天哪...我已按照托管公司提供的如何设置 ngnix + node.js 的说明进行操作。在尝试路由其他路径时,我已经在 404 上停留了好几天。感谢您的回答!
  • 非常感谢您!由于这条愚蠢的线,您刚刚结束了我 3 天的调试。另请注意,具有不同要求的不同位置设置可能很重要,以防其他地方像我一样需要 try_files。
  • 您好,您能帮帮我吗,我正在尝试将我的 / 路由加载为我的主页,但 nginx 一直显示自己的主页。另外,当我尝试访问路由 /api 时,我不断收到 nginx 错误。这个proxy_pass http://localhost:5000; 有什么意义,而不是表明你的公共 ipv4 地址
猜你喜欢
  • 2020-06-16
  • 2020-10-05
  • 2020-05-31
  • 2016-02-24
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 2020-06-17
  • 2021-02-07
相关资源
最近更新 更多