【问题标题】:How to Run C# ASP.NET Core 2.1 and Node.js with Different Ports in Nginx?如何在 Nginx 中使用不同的端口运行 C# ASP.NET Core 2.1 和 Node.js?
【发布时间】:2019-05-05 19:29:33
【问题描述】:

所以我在我的虚拟服务器(virtualbox)上安装了 Nginx、Node.js 和 C# ASP.NET Core 2.1,目前在每个单独的端口上运行。

Node.js 在 localhost:3000 上运行。

.NET Core 在 localhost:5000 上运行。

但是我想在这种情况下制作自定义 URI。如果用户访问根站点(只有“/”),那么它将转到 Node.js 应用程序。如果用户访问另一个页面(在这种情况下,如果用户访问“/api”),那么我希望用户进入 .NET Core 应用程序。

现在,如果我访问根站点,它可以正常工作。一个例子我访问 192.168.56.2(这是我的虚拟服务器 IP),然后浏览器会打开 Node.js 应用程序。但是如果我访问192.168.56.2/api,就会返回404错误码。

这是我的/etc/nginx/sites-available/default 配置:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm;

    root /var/www/html;

    server_name _;

    # Front-end : Node.js
    location / {
           proxy_pass           http://localhost:3000;
           proxy_http_version   1.1;
           proxy_set_header     Upgrade $http_upgrade;
           proxy_set_header     Connection 'upgrade';
           proxy_set_header     Host $host;
           proxy_cache_bypass   $http_upgrade;
    }

    # Back-end : C# ASP.NET Core 2.1
    location /api/ {
        proxy_pass              http://localhost:5000;
        proxy_http_version      1.1;
        proxy_set_header        Upgrade $http_upgrade;
        proxy_set_header        Connection keep-alive;
        proxy_cache_bypass      $http_upgrade;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
    }
}

在我的 C# 代码中,在生成运行 dotnet new webapp -o mywebsite 的代码后,除了 Properties/launchSettings.json 之外,我没有更改任何内容(我将 localhost:5001 删除为仅 localhost:5000)。

我是否在 Nginx 上配置错误?或者我应该更改我的 C# 代码中的某些内容吗?

【问题讨论】:

  • 如果你尝试访问access 192.168.56.2/api/会发生什么?尾部的斜线可能会有所作为。

标签: c# node.js nginx asp.net-core .net-core


【解决方案1】:

这是因为您需要在前端端点和后端端点之间进行适当的映射。

如果您的 /api 端点在您的 ASP.NET 应用程序中不期望 /api 前缀,那么您必须在其 http://nginx.org/r/proxy_pass 规范中包含一个尾部斜杠,这将导致 nginx 创建 @ 的映射前端是 987654325@,后端是 /,例如:

location /api/ {
    proxy_pass http://localhost:5000/; # trailing slash is important for mapping!
}

更多详情请访问ServerFault QA pair

【讨论】:

  • @KushalMK 你链接的问题可能是这个问题标题的我感觉幸运的结果,但所描述的问题是 100% 不相关的。
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2021-12-16
  • 2017-11-28
  • 2014-01-12
  • 2018-01-14
相关资源
最近更新 更多