如何在Nginx中运行具有不同端口的C#ASP.NET Core 2.1和Node.js?

imb*_*ila 14 c# nginx node.js .net-core asp.net-core

所以我在我的虚拟服务器(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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

cns*_*nst 10

这是因为您需要在前端端点和后端端点之间进行正确的映射.

如果您的/api端点不指望/api你的ASP.NET应用程序中的前缀,则必须包括它的一个斜线http://nginx.org/r/proxy_pass规范,这将导致nginx的创建的映射/api/上前端与/后端,例如:

location /api/ {
    proxy_pass http://localhost:5000/; # trailing slash is important for mapping!
}
Run Code Online (Sandbox Code Playgroud)

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