【问题标题】:How do you serve static files from an nginx server acting as a reverse proxy for a nodejs server?您如何从充当 nodejs 服务器的反向代理的 nginx 服务器提供静态文件?
【发布时间】:2015-06-05 15:35:19
【问题描述】:

我当前的 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 提供静态文件?

【问题讨论】:

  • 如果您要如此居高临下,您至少可以链接它,然后我将删除我的问题。我已经看过了,但找不到它。

标签: node.js nginx


【解决方案1】:

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

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

这使用alias directive。 然后你可以在localhost:8080/static/some_file.css打文件

附:您不需要当前设置的rootindex。 (rootalias 相似,但有轻微的difference in usage

【讨论】:

  • 我想要的是,即使 static 不在 URI 中,也可以提供 /static 中的内容 ...
  • @dscan 然后您可以将您的位置块设置为location / { 并将别名设置为指向您的静态文件
  • 但是location / 会直接干扰try {} 块和路由到应用服务器本身?请求路径是否按从上到下的顺序进行测试?因为如果应用程序内部没有路由,应用程序服务器将接受任何内容和 404。
【解决方案2】:

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

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 帖子:


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

【讨论】:

  • try_files $uri /$uri @nodejs; 应该是try_files $uri $uri/ @nodejs;
  • 这个配置意味着nginx首先尝试服务静态文件,如果找不到,则重定向到nodejs服务器?
  • @HS 是的,这正是它的意思。
  • @garkin 同意了,但我想知道当时没有明确的/public/ 文件夹怎么做。我知道,可以从几乎任何通向文件的路径提供文件,这可能是可利用的。
  • 这在根 url 上执行错误 403。修复:更改为 try_files $uri @nodejs; 以便 nginx 只尝试服务文件,而不是目录。
猜你喜欢
  • 2014-07-25
  • 2017-08-16
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2016-05-23
  • 2023-03-13
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多