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?
Best Answer
Instead of
I woule have used:
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: