dotnet / dotnet/aspnetcore

Relative paths with Microsoft.AspNetCore.Rewrite not working

Open
#45,306 2 comments 0 reactions 0 assignees View on GitHub
area-networking
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

I expect the Rewriter to redirect exactly to the String in the Options, but it
adds a leading slash, which makes it impossible to have realtive redirects.

This are the Options of Microsoft.AspNetCore.Rewrite

![image](https://user-images.githubusercontent.com/7533842/204246809-b0ef1fba-7687-4c3f-a16d-f1d823384a72.png)
```
var options = new RewriteOptions()
.AddRedirect(@"^app$", "app/")
.AddRedirect(@"^approval$", "approval/");
```

This is the Redirect it Results in

![image](https://user-images.githubusercontent.com/7533842/204243628-27a50038-113a-4663-9f43-36495de12a0c.png)

This does a redirect to the root of the domain instead to an subfolder. If your running in k8s cluster,
or whatever container which is mounted by external rewrite rules as sub directory, this leads to big problems ;-(

Line with Problem in Code:
https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/Rewrite/src/RedirectRule.cs#L87

Also in this context the docs are strange/wrong ^regex should not match on leading '/'
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-7.0

![image](https://user-images.githubusercontent.com/7533842/204244884-775c4201-98e6-4a1f-9715-65dbfc173850.png)

2nd Bad Code (change string before Regex!):
=> https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/Rewrite/src/RedirectRule.cs#L47

our current custom middleware working work-around which works ;-)
```
app.Use(async (context, next) =>
{
if (context.Request.Path.ToString().ToLower().Equals("/app")) { context.Response.Redirect("app/"); return; }
if (context.Request.Path.ToString().ToLower().Equals("/approval")) { context.Response.Redirect("approval/"); return; }
await next.Invoke();
});
```

### Expected Behavior

302 or 301 => Redirect.Location = "app/" not "/app/"
as long I don't put "/" in the redirect string in the options

### Steps To Reproduce

see bug description.

try to do a relative redirect from subfolder trailing slash with the rewriteoptions
domain/appname/app => domain/appname/app/

### Exceptions (if any)

🚀 keep on rocking with the net core framework. great work!

### .NET Version

net core >=6

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.