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

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

我当前的 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;
    }
}

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

您可能需要在 server 中为静态文件添加另一个 location 块。

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

这里使用了alias directive。 然后你可以点击 localhost:8080/static/some_file.css

的文件

P.S。您不需要当前设置的 rootindex。 (rootalias 相似,略有 difference in usage

我使用这个新配置解决了它:

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;
    }
}

感谢以下 Stack Overflow post:


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