NginX proxying Nodejs/Express - 404 on static file

2019-02-27 03:33发布

I have a setup with NginX which serves a php website off the root from /var/www and proxies Nodejs/Express on a particular subdirectory on my server. Here is the relevant configuration for Nodejs in /etc/nginx/sites-enabled/default inside the server{} block:

location /subdir/ {
    proxy_pass http://localhost:8000;
    proxy_redirect off;
    proxy_http_version 1.1
    proxy_set_header X-Real-IP $remote_addr;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Nginx-Proxy true;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_cache_bypass $http_upgrade;
}

This is the code for my Nodejs application:

var port = 8000;
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app).listen(port);
var io = require('socket.io').listen(server);

app.use(express.static(__dirname + '/site'));
app.get('/subdir/', function(req, res) {
    res.sendFile(__dirname + '/site/index.html');
});

server.listen(port, function() {
    console.log("Listening on port " + port + "...");
});

io.on('connection', function(socket) {
    console.log("A user connected");
});

For the most part, everything works fine, when I access my server at http://server/subdir/, I get the index.html file that I expect. However, I get 404 errors on the other static content like http://server/subdir/css/main.css 404 (Not Found) or a Cannot GET /sudir/css/main.css error when I directly access the file in my browser even though the file is there.

Why is it that Node/Express cannot find my static content?

Alternatively, how can I get NginX to serve my static content? I even tried adding a root statement in the location /subdir/ {} block to point to the Node/Express project directory but still I get 404 errors.

1条回答
We Are One
2楼-- · 2019-02-27 04:06

If you want to access the static files through a different route, pass the route as the first argument :

You can use app.use('/static', express.static(__dirname + '/public'));

and a GET to http://server/static/css/main.css will serve main.css

Also if you want to serve static files through nginx this article is a good start: USING NGINX TO AVOID NODE.JS LOAD

查看更多
登录 后发表回答