如何使用Express和NGINX设置路线?

n9vozmp4  于 2022-12-03  发布在  Nginx
关注(0)|答案(2)|浏览(161)

我试图配置一个带有NGINX的Express服务器作为反向代理。NGINX服务于静态文件,Express服务于动态内容。
问题:正常的根链接(website.com)正常工作,但当我导航到(website.com/api)时,NGINX显示404
这是我的博客:

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;
    }
}
n8ghc7c1

n8ghc7c11#

尝试删除以下行:

try_files $uri $uri/ =404;

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

64jmpszr

64jmpszr2#

在我的例子中,server中的location属性是:

location {
    proxy_pass http://localhost:3000;
    rewrite ^/(.*)$ /$1 break; # --> this helps
}

相关问题