ASP.NET 5.0 红隼服务器与nginx
本文关键字:服务器 nginx NET ASP | 更新日期: 2023-09-27 17:55:35
我正在尝试在 Ubuntu 上托管一个 ASP.NET 5.0(beta 4)网站。我已经将 Kestrel 与 nginx 配置为反向代理,但有几个问题阻止将其用于生产站点:
- HTTP 404错误页面是空白的 - 有没有办法配置 ASP.NET/Kestrel 或nginx来发送自定义页面而不是空白页面?
- 如何配置 URL 重写 - 例如,除了 ASP.NET 内容之外,我还有一些静态.htm页面,我想重写这些页面以在没有 .htm 扩展名的情况下提供它们
感谢Matt DeKrey的建议,我使用两个中间件完成了这项工作。
对于自定义 404 错误页面,我使用了:
public class CustomErrorMiddleware
{
private readonly RequestDelegate next;
public CustomErrorMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync("/errors/404.html");
}
}
对于 URL 重写,我使用了:
public class UrlRewriteMiddleware
{
private readonly RequestDelegate next;
public UrlRewriteMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
// Redirect from /some/page.htm to /some/page
Regex r1 = new Regex("^/some/[a-zA-Z0-9]+''.htm$");
if (r1.IsMatch(context.Request.Path.Value))
{
context.Response.Redirect(context.Request.Path.Value.Substring(0, context.Request.Path.Value.Length - 4));
return;
}
// Rewrite from /some/page to /some/page.htm
Regex r2 = new Regex("^/some/[a-zA-Z0-9]+$");
if (r2.IsMatch(context.Request.Path.Value))
context.Request.Path = new PathString(context.Request.Path.Value + ".htm");
await next(context);
}
}
然后修改Startup.cs
以使用这些中的每一个。中间件按指定的顺序运行,因此需要首先重写 URL 以在收到请求时对其进行修改。自定义 404 错误中间件需要排在最后,以捕获任何其他中间件未处理的任何请求。例如:
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<UrlRewriteMiddleware>();
app.UseStaticFiles();
app.UseMvc();
app.UseMiddleware<CustomErrorMiddleware>();
}