URL重写选项:如何排除文件和目录



我在ASP.NET Core中使用URL重写中间件,如果请求不指向现有文件或目录,我将尝试使重写仅在下运行

这是我正在使用的代码:

var options = new RewriteOptions()
.AddRewrite(@"^(.*)$", "index.php/$1", skipRemainingRules: true);
app.UseRewriter(options);

In:Startup::Configure()

在IIS中,使用web.config,我可以定义如下内容:

<rule name="RewriteRule" enabled="true" stopProcessing="false">
<match url="^(.*)$" ignoreCase="true" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
</conditions>
<action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
</rule>

请注意,对于input="{REQUEST_FILENAME}"matchType="IsFile"matchType="IsDirectory"上的negate="true"属性是请求路径。

我不想用AddIISUrlRewrite()加载IIS风格的重写规则集,也不相信它会起作用。

是否可以从ASP.NET Core中的重写请求中排除现有的静态文件?如果是,如何?

我最终做了这样的事情——我的静态文件托管在一个子文件夹下"Web":

var fileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Web"));
app.UseRewriter(new RewriteOptions() { StaticFileProvider = fileProvider }
.Add(context =>
{
if (context.HttpContext.Request.Path.StartsWithSegments("/Web", out var subPath))
{
if (subPath != "/" && context.StaticFileProvider.GetDirectoryContents(subPath).Exists)
{
context.Result = RuleResult.SkipRemainingRules;
}
else if (context.StaticFileProvider.GetFileInfo(subPath).Exists)
{
context.Result = RuleResult.SkipRemainingRules;
}
}
})
.AddRewrite("^Web/(.*)$", "Web/index.html", true));
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = fileProvider,
RequestPath = "/Web",
});

最新更新