如何在托管两个Nginx ASP.NET Core站点的服务器上正确提供wwwroot文件
问题根源
你的Cat站点(端口2000)被Nginx挂载在/cat子路径下,但ASP.NET Core框架不知道这个子路径的存在。当页面使用~/css/catstyles.css时,~会被解析为站点根路径/,最终生成的请求URL是/css/catstyles.css。Nginx收到这个请求后,会匹配到默认的/规则,转发到Dog站点(端口2001),自然找不到Cat站点的静态资源,导致404。
解决方法
方法一:配置ASP.NET Core应用的基路径(推荐)
让Cat站点知道自己运行在/cat子路径下,这样框架会自动把~解析为/cat,生成正确的静态资源URL。
修改Cat站点的Program.cs:
var builder = WebApplication.CreateBuilder(args); // 设置应用的路径基址 builder.WebHost.UseUrls("http://localhost:2000/cat"); // 或者使用PathBase配置 builder.Services.AddRouting(options => options.PathBase = "/cat"); // 其他服务配置... var app = builder.Build(); // 如果使用了PathBase,需要在中间件管道最前面添加这行 app.UsePathBase("/cat"); // 静态文件中间件必须在UsePathBase之后 app.UseStaticFiles(); // 其他中间件(路由、授权等)... app.Run();
配置完成后,Cat站点生成的静态资源URL会变成/cat/css/catstyles.css,Nginx会匹配到/cat规则,转发到端口2000的Cat站点,正确获取资源。
方法二:修改Nginx配置拦截静态资源请求
如果不想改动ASP.NET Core代码,可以在Nginx配置中添加更具体的规则,把Cat站点的静态资源请求直接转发到端口2000。
更新后的Nginx配置:
server { server_name staging.myexample.com; server_tokens off; gzip off; # 优先匹配Cat站点的静态资源路径 location ~ ^/cat/(css|js|images|fonts)/ { proxy_pass http://localhost:2000; 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; proxy_redirect off; } location / { proxy_pass http://localhost:2001; 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; default_type application/json; proxy_redirect off; } location /cat { proxy_pass http://localhost:2000; 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; default_type application/json; proxy_redirect off; } }
注意:Nginx的location规则匹配是从上到下优先匹配更具体的规则,所以必须把静态资源规则放在/规则前面。这样请求/cat/css/catstyles.css时会被正确转发到Cat站点。
内容的提问来源于stack exchange,提问作者LePrinceDeDhump
相关产品推荐
相关产品推荐

