ASP.NET Core 7.0中AddRewrite为何触发HTTP 301重定向?
ASP.NET Core中AddRewrite触发301重定向的原因及解决办法
我在ASP.NET Core中添加了Rewrite规则,但却出现了重定向现象。原本以为AddRewrite的核心作用是对HTTP客户端保持透明。
完整代码
using System.Collections.Generic; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Configuration; using MyProject.Preview.Configuration; using Microsoft.AspNetCore.Rewrite; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseHttpLogging(); var options = new RewriteOptions().AddRewrite(@"^p/([a-zA-Z0-9]*)/w/([a-zA-Z0-9-]*)","/preview/$1/workspace/$2/wwwroot",skipRemainingRules: true); app.UseRewriter(options); app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = new PhysicalFileProvider(Path.Combine(builder.Configuration.GetSection("Pad").GetValue<string>(nameof(PadConfiguration.StorageRootPath)), "artifacts")), RequestPath = "/preview", DefaultFileNames = new List<string> { "index.html" } }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(builder.Configuration.GetSection("Pad").GetValue<string>(nameof(PadConfiguration.StorageRootPath)), "artifacts")), RequestPath = "/preview", ServeUnknownFileTypes = true, }); app.Run();
CURL输出
curl -I http://localhost:5033/p/d8f7i885d/w/583bdffe-09bd-4a03-8b4e-5006f743c617 HTTP/1.1 301 Moved Permanently Date: Wed, 26 Jul 2023 04:52:22 GMT Server: Kestrel Location: http://localhost:5033/preview/d8f7i885d/workspace/583bdffe-09bd-4a03-8b4e-5006f743c617/wwwroot/
问题:为何RewriteOptions会触发重定向?
原因分析
重定向并非由Rewrite中间件触发,而是UseDefaultFiles中间件的默认行为导致:
- 你的Rewrite规则将请求路径重写为
/preview/xxx/workspace/xxx/wwwroot,这个路径对应服务器上的一个目录(wwwroot是文件夹)。 UseDefaultFiles中间件在处理目录请求时,如果请求路径没有以/结尾,会自动发送301重定向到带/的路径,之后再返回目录下的默认文件(比如index.html)。
解决办法
方案一:修改Rewrite规则,让目标路径以/结尾
修改重写规则的目标路径,添加末尾斜杠,这样请求直接匹配带斜杠的目录路径,避免触发重定向:
var options = new RewriteOptions().AddRewrite(@"^p/([a-zA-Z0-9]*)/w/([a-zA-Z0-9-]*)","/preview/$1/workspace/$2/wwwroot/",skipRemainingRules: true);
方案二:禁用UseDefaultFiles的自动重定向行为
通过设置RedirectToAppendTrailingSlash为false,关闭中间件的重定向逻辑:
app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = new PhysicalFileProvider(Path.Combine(builder.Configuration.GetSection("Pad").GetValue<string>(nameof(PadConfiguration.StorageRootPath)), "artifacts")), RequestPath = "/preview", DefaultFileNames = new List<string> { "index.html" }, RedirectToAppendTrailingSlash = false // 禁用自动添加斜杠的重定向 });
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

