Reputation: 11
In short, Nginx and Node JS are both running on the same server 10.0.0.120. I can access a Node app via http://10.0.0.120:3000, all stylesheets are loaded properly.
I want the Node app to be accessed via 10.0.0.120/abc/ so I had the following Nginx setup in /etc/nginx/sites-available/default
location /abc/ {
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Now that 10.0.0.120/abc/ can reach the Node app but returns without stylesheet loaded because the relative path maps into 10.0.0.120/stylesheets, which obviously does not exist.
On the NodeJS side, I simply used the Express template,in which public
folder is used for serving static files.
app.use(express.static(path.join(__dirname, 'public')));
The Node directory tree is shown below
Node App
|
|── public
| ├── images
| ├── javascripts
│ │ ├── bootstrap.js
│ │ ├── bootstrap.min.js
│ │ └── jquery.min.js
│ └── stylesheets
│ ├── animate.css
│ ├── bootstrap.css
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
How should I change the Nginx setting to fix the issue?
Upvotes: 1
Views: 1476
Reputation: 2937
Try using app.use(express.static('public'))
. Express should recognize without path.join.
Upvotes: 1
Reputation: 4678
It's better to serve static files directly by nginx, its more efficient and you can easily manage cache there
server {
listen YOUR_APP_PORT;
server_name YOUR_SERVER_NAME;
location /abc/ {
YOUR_STANDARD_ROUTING_CONFIGURATION
}
location ~^\/(images|stylesheets|fonts|javascripts) {
expires 1M;
access_log off;
add_header Cache-Control "public";
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET;
add_header Access-Control-Allow-Headers X-Requested-With,content-type;
add_header Access-Control-Allow-Credentials true;
root YOUR_APPLICATION_PATH/public;
}
}
Upvotes: 1
Reputation: 5245
app.use(express.static(path.join(__dirname, 'public')));
from your code.Configure nginx proxy (conf/nginx.conf
file) similar below.
http {
...
server {
listen 2000;
server_name localhost;
root YOUR-APP-PATH/public;
location / {
try_files $uri @backend;
}
location @backend {
proxy_pass http://localhost:3000;
}
...
Run application on 2000
port. Application with static files will be enable on 3000
.
P.S. I'm a not nginx expert but it's work for me.
Upvotes: 1