Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

node.js - How do you serve static files from an nginx server acting as a reverse proxy for a nodejs server?

My current nginx config is this:

upstream nodejs {
    server 127.0.0.1:3000;
}

server {
    listen 8080;
    server_name localhost;
    root ~/workspace/test/app;
    index index.html;

    location / {
        proxy_pass http://nodejs;
        proxy_set_header Host $host ; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

I'm very very new to nginx, but at the very least I know that nginx is better than node/express at serving static files. How can I configure the server so that nginx serves the static files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved it using this new configuration:

upstream nodejs {
    server localhost:3000;
}

server {
    listen 8080;
    server_name localhost;
    root ~/workspace/test/app;

    location / {
        try_files $uri @nodejs;
    }

    location @nodejs {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_pass http://nodejs;
        proxy_set_header Host $host ; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Thanks to the following Stack Overflow post:


How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...