大网数据广告活动
服务器运维问答

Nginx not serving javascript files

· 52CE 我爱测

I have a server running Nginx, and I have two locations in the same server block. I'm using this as a reverse proxy for my node.js express application. /etc/nginx/sites-available/example.com server { server_name example.com www.e…

问题原文

原帖链接 · ajjohnson190 · CC BY-SA 4.0

I have a server running Nginx, and I have two locations in the same server block. I'm using this as a reverse proxy for my node.js express application.

/etc/nginx/sites-available/example.com

server {

server_name example.com www.example.com;

location / {
    proxy_pass http://localhost:8000;
    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;
}

location /otherapp{
    root /home/ubuntu/otherapp;
    proxy_pass http://localhost:4444;
    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;
}
...

The application running on the www.example.com location works as intended, and all the css and js files load. But on the www.example.com/otherapp location, the html file is served but the js fails to load with a status 404. The browser sends a GET to https://example.com/index.js

Express Code for /otherapp

const express = require('express');
const app = express();

//things for express
app.use(express.static(__dirname+'/public')); //static directory


//qrcode is base route
app.get('/qrcode', function(req, res){
    res.sendFile(__dirname+'/public/index.html')
});


//start server
var port = 4444;
var ip;
if(process.env.NODE_ENV == "production"){
    ip = 'serverip';
}
else{
    ip = 'localhost';
}
app.listen(port, ip, function(){
    console.log(`starting server on ${ip}:${port}`)
});

/home/ubuntu/otherapp/public/index.html

...
<script src="./index.js"></script>
...

index.js is located in the same folder as index.html

How can I fix this?

已采纳解答

原帖链接 · SYN · CC BY-SA 4.0

Instead of

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

I woule have used:

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

Though this is mostly useful during devs, when I do not have a webserver aside from NodeJS. Otherwise, I'ld rather serve static file with Nginx, in your case:

location /otherapp/public {
    root /home/ubuntu/otherapp;
}

location /otherapp {
    proxy_pass http://localhost:4444;
    xxx
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-12-04)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。