首页 > 解决方案 > 如何在 Nginx 中使用不同的端口运行 C# ASP.NET Core 2.1 和 Node.js?

问题描述

所以我在我的虚拟服务器(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# 代码中,在使用 running 生成代码后dotnet new webapp -o mywebsite,除了 Properties/launchSettings.json 之外,我没有更改任何内容(我将 localhost:5001 删除为仅 localhost:5000)。

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

标签: c#node.jsnginxasp.net-core.net-core

解决方案


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

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

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

有关ServerFault QA 对的更多详细信息。


推荐阅读