您如何从充当 nodejs 服务器的反向代理的 nginx 服务器提供静态文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29383159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:36:06  来源:igfitidea点击:

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

node.jsnginx

提问by m0meni

My current nginx config is this:

我当前的 nginx 配置是这样的:

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?

我对 nginx 非常陌生,但至少我知道 nginx 在提供静态文件方面比 node/express 更好。如何配置服务器以便 nginx 提供静态文件?

回答by m0meni

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:

感谢以下 Stack Overflow 帖子:



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

如何直接使用 NGINX 服务所有现有的静态文件,但将其余的代理到后端服务器。

回答by Sanketh Katta

You'll probably want another locationblock within your serverfor the static files.

您可能需要在静态文件中使用另一个locationserver

location /static {
  alias /path/to/static/files;
}

This uses the alias directive. Then you can hit files at localhost:8080/static/some_file.css

这使用别名指令。然后你可以点击文件localhost:8080/static/some_file.css

P.S. You don't need the rootor indexthat you have set currently. (rootis similar to aliaswith a slight difference in usage)

PS 您不需要当前设置的rootindex。(root类似于用法alias略有不同