首页 > 解决方案 > nginx 作为反向代理:当位置不是默认位置时重定向错误

问题描述

我正在尝试将 nginx 设置为 ASP .NET Core API 的反向代理。
这是我的 nginx 服务器配置(基于答案):

server {
    listen        80;

    location = /crypto-api {
             return 302 /crypto-api/;
    }

    location /crypto-api/ {
        proxy_pass         http://localhost:6103/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

应用程序支持 OpenAPI 并在内部具有 Swagger UI (Swashbucke)。当用户尝试浏览根目录时,API 会将他重定向到 Swagger UI 页面。

重定向中间件非常简单:

        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path == "/")
            {
                context.Response.Redirect("/swagger");
                return;
            }

            await next(context);
        }

当位置是默认位置('/')时,这可以正常工作,如如何. 但如果位置设置如上,我在导航到http://192.168.211.130/crypto-api.

在浏览器中导航尝试 URL 后是:

http://192.168.211.130/swagger

代替

http://192.168.211.130/crypto-api/swagger

如果我直接输入 Swagger UI 页面地址:

http://192.168.211.130/crypto-api/swagger/index.html

我可以看到页面,但由于地址错误,无法加载 OpenAPI 规范: 在此处输入图像描述

这是我第一次使用 nginx,所以我不知道如何解决这个问题。如果这很重要,我正在使用基于 Fedora 的 Linux 发行版。

标签: c#asp.net-corenginxnginx-reverse-proxy

解决方案


推荐阅读