使用 nginx 作为节点反向代理服务根静态文件

Serve root static file with nginx as node reverse proxy

我有一个使用 nginx 作为反向代理的 nodejs 服务器。那部分没问题,静态文件位置设置正确。但是我希望根地址为静态 html 文件提供服务,而且我不知道如何配置 nginx,以便根 url 不会重定向到节点应用程序。这是我的服务器块:

upstream promotionEngine {
 server 127.0.0.1:3001;
}

server {
    listen       3000;
    server_name  localhost;
    root C:/swaven/dev/b2b.pe/promotionEngine/templates/;
    index index.html;

    location / {
      proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://promotionEngine;
        proxy_redirect off;
    }

    location /public/ {
      alias C:/swaven/dev/b2b.pe/promotionEngine/public/;
    }

    location /assets/ {
      alias C:/swaven/dev/b2b.pe/promotionEngine/assets/;
    }
}

http://localhost:3000/ping 和 http://localhost:3000/public/js/riot.js 已正确提供服务。
但是 http://localhost:3000 一直被发送到节点服务器,我希望它成为 return 静态 index.html。如果我删除 / location 块,html 文件将正确提供。我将如何配置该位置以作为除根以外的所有 url 的反向代理?

Something like this, adjust for your own use case.

http {
    map $request_uri $requri {
        default          1;
        /                0;
    }
...........
    server {
        listen       80;
        server_name  www.mydomain.eu;
        root   '/webroot/www.mydomain.eu’;
        if ($requri) { return 301 https://www.mydomain.eu$request_uri; }
        location / {
            ..........
        }
    }

您可以使用 =/ 这种类型的位置由于查找而具有更高的优先级:

location =/ {
  root ...
}

此请求甚至不会尝试到达其他位置。

已更新:(基于评论和讨论)

您将需要 2 个确切位置块。一个拦截 / 位置,另一个只提供 /index.html.

nginx docs 上描述了一个确切的位置块:

Also, using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates.

仅使用 index 指令是行不通的。因为 nginx creates an internal redirect 允许其他块匹配 index.html。哪个被你的代理块拾取。

upstream promotionEngine {
 server 127.0.0.1:3001;
}

server {
    listen       3000;
    server_name  localhost;

    # Do an exact match on / and rewrite to /index.html
    location = / {
      rewrite ^$ index.html;
    }

    # Do an exact match on index.html to serve just that file
    location = /index.html {
      root C:/swaven/dev/b2b.pe/promotionEngine/templates/;
    }

    # Everything else will be served here
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass http://promotionEngine;
      proxy_redirect off;
    }

    location /public/ {
      alias C:/swaven/dev/b2b.pe/promotionEngine/public/;
    }

    location /assets/ {
      alias C:/swaven/dev/b2b.pe/promotionEngine/assets/;
    }
}