How to setup routes with Express and NGINX?

左心房为你撑大大i 提交于 2020-01-01 11:57:49

问题


I'm trying to configure an Express server with NGINX as a reverse proxy. NGINX to serve static files, and Express for the dynamic content.

Problem : The normal root link works (website.com) , but when I navigate to (website.com/api), I get a 404 from NGINX


This is my 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');
});

This is my NGINX Config file:

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

回答1:


Try to remove this line:

try_files $uri $uri/ =404;

With this directive nginx tries to serve a static file (or directory), and returns 404 if there is no such file.



来源:https://stackoverflow.com/questions/44668559/how-to-setup-routes-with-express-and-nginx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!