c# - 如何在 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# 代码中的某些内容吗?
解决方案
这是因为您需要在前端端点和后端端点之间进行适当的映射。
如果您的/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 对的更多详细信息。
推荐阅读
- scala - 创建子类型的空 IndexedSeq 并使用 TailRec
- laravel - 在查询回调中返回关键字
- unity3d - 如何将 MixedReality-ToolKit 实施到现有的 HoloLens 项目中?
- azure-cosmosdb - 在对象列表中查询,查找不同对象的一些属性(CosmosDB SQL API)
- javascript - 遍历已解析的 JSON 时未定义
- postgresql - 从输出的第二行提取数据
- python - Django:为什么有些模板没有检测到?
- python - 如何使用 Python3 连接到 PI Webservice
- python - Python识别(转换)文本到日期
- python - 解包 2d 元组列表