简体   繁体   English

在 nginx 反向代理后面设置 ASP NET Core MVC 应用程序的虚拟路径

[英]Set Virtual Path to ASP NET Core MVC Application behind nginx reverse proxy

I have an ASP NET Core application running inside a docker container and I'm trying to access this application using a NGINX Reverse Proxy that I built inside another docker container.我有一个 ASP NET Core 应用程序在 docker 容器中运行,我正在尝试使用我在另一个 docker 容器中构建的 NGINX 反向代理访问该应用程序。

When I try to access the MVC Application using the virtual path that I configured on Nginx .conf files, like this: " http://localhost:1000/mvcapp/ ", all the css, js and othrr static files that uses relative paths are not found, because mvc doesnt handle the virtual path to configure correctly the path for those files.当我尝试使用我在 Nginx .conf 文件上配置的虚拟路径访问 MVC 应用程序时,像这样:“ http://localhost:1000/mvcapp/ ”,所有使用相对路径的 css、js 和 othrr 静态文件找不到,因为 mvc 不处理虚拟路径以正确配置这些文件的路径。

my url: http://localhost:1000/mvc我的网址: http://localhost:1000/mvc

path that mvc builts: href="/css/bootstrap.css" mvc 构建的路径:href="/css/bootstrap.css"

the correct way that mvc should built: href="mvc/css/bootstrap" mvc 应该构建的正确方法:href="mvc/css/bootstrap"

Sounds like your reverse proxy works in a way that maps /mvcapp to / as below:听起来您的反向代理的工作方式是将/mvcapp映射到/ ,如下所示:

location /mvcapp {
    proxy_pass         http://localhost:6009/;    # assume you expose the 6009 port
    ...
}

If that's the case, that's because the proxy cuts off the /mvcapp prefix.如果是这种情况,那是因为代理切断了/mvcapp前缀。 And your MVC app doesn't realize the virtual app path is /mvcapp .并且您的 MVC 应用程序没有意识到虚拟应用程序路径是/mvcapp To fix that, add a middleware to set the PathBase explicitly:要解决这个问题,请添加一个中间件来显式设置PathBase

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // add this middleware as the first one
    app.Use((context, next)=> {
        context.Request.PathBase = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
        return next();
    });          
    //  ... other middlewares
}

And pass the ASPNETCORE_APPL_PATH environment when starting the docker.并在启动ASPNETCORE_APPL_PATH时传递ASPNETCORE_APPL_PATH环境。 For example, you can pass the environment in the command:例如,您可以在命令中传递环境:

## assume you want to map the port 6009 to 80, 
##     and the image name is nginxtocore
docker run -p 6009:80 -e ASPNETCORE_APPL_PATH='/mvcapp'  nginxtocore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM