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

14

所以我在我的虚拟服务器(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/会发生什么?那个斜杠可能会有所不同。 - Dave
1个回答

11

这是因为您需要在前端端点和后端端点之间建立正确的映射关系。

如果您的/api端点不希望在ASP.NET应用程序中包含/api前缀,则必须在其http://nginx.org/r/proxy_pass规范中包含一个尾部斜杠,这将导致nginx在前端上创建/api/与后端上的/之间的映射关系,例如:

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

更多细节可以在ServerFault问答对中获得。


@KushalMK,您所链接的问题可能是与此问题标题相似的I'm-feeling-lucky结果,但所描述的问题100%无关。 - cnst

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接